Overlay one image over another - javascript

I'm trying to overlay 1 image over the top of another but cant seem to work it out - my code throws no errors but doesn't output the requested image modification. Can someone point me in the right direction?
Here is my code
const user = message.mentions.users.first();
if (args[0] === undefined) {
message.channel.send("You can't jail yourself, dummy!")
} else {
var images = [user.avatarURL({ format: 'png', dynamic: true, size: 256 }), 'https://i.pinimg.com/originals/7b/51/9a/7b519a3422f940011d34d1f9aa75f683.png']
var jimps = []
//turns the images into readable variables for jimp, then pushes them into a new array
for (var i = 0; i < images.length; i++){
jimps.push(jimp.read(images[i]))
}
//creates a promise to handle the jimps
await Promise.all(jimps).then(function(data) {
return Promise.all(jimps)
}).then(async function(data){
// --- THIS IS WHERE YOU MODIFY THE IMAGES --- \\
data[0].composite(data[1], 0, 0) //adds the second specified image (the jail bars) on top of the first specified image (the avatar). "0, 0" define where the second image is placed, originating from the top left corner
//you CAN resize the second image to fit the first one like this, if necessary. The "100, 100" is the new size in pixels.
data[1].resize(100,100)
//this saves our modified image
data[0].write(`\Users\jmoor\Pictures\JIMP Test\test.png`)
})
message.channel.send(`${user.username} has been jailed!`, {file: `\Users\jmoor\Pictures\JIMP Test\test.png`})
}
I have defined jimp above and also am using a command handler I made.

Use this:
const user = message.mentions.users.first() //get The first user mentioned
if (!user) return message.reply("Who do you wanna send to jail?")//return if no user was mentioned
var bars = "https://i.pinimg.com/originals/7b/51/9a/7b519a3422f940011d34d1f9aa75f683.png"
var pfp = user.avatarURL({ format: 'png', dynamic: true, size: 128 }) //get link of profile picture
var image = await Jimp.read(pfp)//read the profile picture, returns a Jimp object
//Composite resized bars on profile picture
image.composite((await Jimp.read(bars)).resize(128, 128), 0, 0)
//create and attachment using buffer from edited picture and sending it
var image = new Discord.MessageAttachment(await image.getBufferAsync(Jimp.MIME_PNG))
message.reply(image)

Related

Google Sheets. How to get the real range size in pixels

My script converts the selected range into an image, please see. It first creates a public PDF URL and then converts it to PNG.
It works well for small ranges (10-20 rows) and creates a shot including images, charts, sparklines, and formatting.
The problem is with big ranges (100-1000 rows). They contain a border of unknown size and I cannot calculate it.
Heavy borders make rows higher so the image does not fit.
If we have no borders or thin borders, the real image size appears a bit smaller than calculated. This creates an empty space below the image.
My code sample for getting the range size in pixels:
// get row height in pixels
var h = 0;
for (var i = rownum; i <= rownum2; i++) {
if (i <= options.measure_limit) {
size = sheet.getRowHeight(i);
}
h += size
/** manual correction */
if (size === 2) {
h-=1;
} else {
// h -= 0.42; /** TODO → test the range to make it fit any range */
}
if ((i % 50) === 0 && i <= options.measure_limit) {
file.toast(
'Done ' + i + ' rows of ' + rownum2,
'↕📐Measuring height...');
}
}
if (i > options.measure_limit) {
file.toast(
'Estimation: all other rows are the same size',
'↕📐Measuring height...');
}
As you see, I have to loop over all rows which is extremely inefficient. I'd be glad to hear your ideas for code optimization. Now it loops the first 150 rows and next it assumes all other rows have the same height.
Sample Situations
"Small" ranges are that you can see on screen. "Big" ranges have 100+ rows so they do not fit normal screen. As I create screenshots, I tested all possible range sizes.
Case1 - no borders or thin borders
If I select a big range I get the image, and see it has a white space at the bottom. This means the real size of image was slightly smaller than one I get from the Script by calling sheet.getRowHeight(i).
Case1 - heavy borders
If I select a big range I get the image, and see not all rows I've selected are on that image. Some rows at the bottom of the range are missing. This means when I add heavy borders, the real size of rows is bigger than one I get from the Script by calling sheet.getRowHeight(i).
Conclusion
I'd be glad to hear any ideas including JavaScript hacks to remove empty space below the image. If it is currently not possible, please also answer with links to docs.
I believe your goal is as follows.
You want to export the range as an image using Google Apps Script and Javascript.
In order to achieve this, in this question, you want to calculate the row height of the selected cell range.
Issue and workaround:
As our discussions in the comment, in the current stage, when the correct row height of the cell range is trying to be obtained, there are several problems as follows.
When the border is used for the cells, it seems that the row height + the border size is different from the exported result. Ref
Pixel size might not be changed linearly with the value of row height and border size. Ref
When I tested the cell size including the borders, I thought that the tendency of change of size might be different between height and width. Ref
When the row height is the default (21 from getRowHeight) and the text font size in the cell is increased, the value retrieved by getRowHeight is not changed from 21. Ref
There is also issue with wrapping text inside a cell which on my experience also causes errors in a pixel size of cell. Ref
From your question, when the selected cell range is large, the number of pages is more than 2. In this case, all pages cannot be correctly merged as an image.
From the above situation, I'm worried that obtaining the correct size of the selected cells might be difficult. So, I proposed to process this as image processing. Ref I thought that when this process is run with the image processing, the above issues might be able to be avoided.
But, unfortunately, in order to process this as image processing, there is no built-in method in Google Apps Script. But, fortunately, in your situation, it seems that Javascript can be used in a dialog. So, I created a Javascript library for achieving this process as the image processing. Ref
When this Javascript library is used, the sample demonstration is as follows.
Usage:
1. Prepare a Spreadsheet.
Please create a new Spreadsheet and put several values to the cells.
2. Sample script.
Please copy and paste the following script to the script editor of Spreadsheet.
Google Apps Script side: Code.gs
function getActiveRange_(ss, borderColor) {
const space = 5;
const sheet = ss.getActiveSheet();
const range = sheet.getActiveRange();
const obj = { startRow: range.getRow(), startCol: range.getColumn(), endRow: range.getLastRow(), endCol: range.getLastColumn() };
const temp = sheet.copyTo(ss);
const r = temp.getDataRange();
r.copyTo(r, { contentsOnly: true });
temp.insertRowAfter(obj.endRow).insertRowBefore(obj.startRow).insertColumnAfter(obj.endCol).insertColumnBefore(obj.startCol);
obj.startRow += 1;
obj.endRow += 1;
obj.startCol += 1;
obj.endCol += 1;
temp.setRowHeight(obj.startRow - 1, space).setColumnWidth(obj.startCol - 1, space).setRowHeight(obj.endRow + 1, space).setColumnWidth(obj.endCol + 1, space);
const maxRow = temp.getMaxRows();
const maxCol = temp.getMaxColumns();
if (obj.startRow + 1 < maxRow) {
temp.deleteRows(obj.endRow + 2, maxRow - (obj.endRow + 1));
}
if (obj.startCol + 1 < maxCol) {
temp.deleteColumns(obj.endCol + 2, maxCol - (obj.endCol + 1));
}
if (obj.startRow - 1 > 1) {
temp.deleteRows(1, obj.startRow - 2);
}
if (obj.startCol - 1 > 1) {
temp.deleteColumns(1, obj.startCol - 2);
}
const mRow = temp.getMaxRows();
const mCol = temp.getMaxColumns();
const clearRanges = [[1, 1, mRow], [1, obj.endCol, mRow], [1, 1, 1, mCol], [obj.endRow, 1, 1, mCol]];
temp.getRangeList(clearRanges.map(r => temp.getRange(...r).getA1Notation())).clear();
temp.getRange(1, 1, 1, mCol).setBorder(true, null, null, null, null, null, borderColor, SpreadsheetApp.BorderStyle.SOLID);
temp.getRange(mRow, 1, 1, mCol).setBorder(null, null, true, null, null, null, borderColor, SpreadsheetApp.BorderStyle.SOLID);
SpreadsheetApp.flush();
return temp;
}
function getPDF_(ss, temp) {
const url = ss.getUrl().replace(/\/edit.*$/, '')
+ '/export?exportFormat=pdf&format=pdf'
// + '&size=20x20' // If you want to increase the size of one page, please use this. But, when the page size is increased, the process time becomes long. Please be careful about this.
+ '&scale=2'
+ '&top_margin=0.05'
+ '&bottom_margin=0'
+ '&left_margin=0.05'
+ '&right_margin=0'
+ '&sheetnames=false'
+ '&printtitle=false'
+ '&pagenum=UNDEFINED'
+ 'horizontal_alignment=LEFT'
+ '&gridlines=false'
+ "&fmcmd=12"
+ '&fzr=FALSE'
+ '&gid=' + temp.getSheetId();
const res = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } });
return "data:application/pdf;base64," + Utilities.base64Encode(res.getContent());
}
// Please run this function.
function main() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const temp = getActiveRange_(ss, "#000000");
const base64 = getPDF_(ss, temp);
const htmltext = HtmlService.createTemplateFromFile('index').evaluate().getContent();
htmltext = htmltext.replace(/IMPORT_PDF_URL/m, base64);
const html = HtmlService.createTemplate(htmltext).evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE);
SpreadsheetApp.getUi().showModalDialog(html, 'sample');
ss.deleteSheet(temp);
}
function saveFile(data) {
const blob = Utilities.newBlob(Utilities.base64Decode(data), MimeType.PNG, "sample.png");
return DriveApp.createFile(blob).getId();
}
HTML & Javascript side: index.gs
Here, I used a Javascript library of CropImageByBorder_js for processing this as the image processing.
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tanaikech/CropImageByBorder_js#latest/cropImageByBorder_js.min.js"></script>
<canvas id="canvas"></canvas>
<script>
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
const base64 = 'IMPORT_PDF_URL'; //Loaading the PDF from URL
const cvs = document.getElementById("canvas");
pdfjsLib.getDocument(base64).promise.then(pdf => {
const {numPages} = pdf;
if (numPages > 1) {
throw new Error("Sorry. In the current stage, this sample script can be used for one page of PDF data. So, please change the selected range to smaller.")
}
pdf.getPage(1).then(page => {
const viewport = page.getViewport({scale: 2});
cvs.height = viewport.height;
cvs.width = viewport.width;
const ctx = cvs.getContext('2d');
const renderContext = { canvasContext: ctx, viewport: viewport };
page.render(renderContext).promise.then(async function() {
const obj = { borderColor: "#000000", base64Data: cvs.toDataURL() };
const base64 = await CropImageByBorder.getInnerImage(obj).catch(err => console.log(err));
const img = new Image();
img.src = base64;
img.onload = function () {
cvs.width = img.naturalWidth;
cvs.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
}
google.script.run.withSuccessHandler(id => console.log(id)).saveFile(base64.split(",").pop());
});
});
});
</script>
3. Testing
When you test this script, please select the cells and run main(). By this, the selected cells are exported as an image (PNG) to the root folder as follows. In this case, you can see the above demonstration.
4. Flow.
In this sample script, the following flow is used.
Manually select the cells, and run the script of main().
At the script, the selected cells enclosed by the single row and column are created as a temporal sheet.
Export the temporal sheet as a PDF data as base64. Here, the PDF data is sent to Javascript side.
Convert 1st page of PDF data to an image using PDF.js.
Cropping the selected cells using CropImageByBorder_js, and return the result image to Google Apps Script side.
Save the image as a file to Google Drive.
LIMITATION:
In this sample script, it supposes that the selected range is put on one PDF page. So, when you select a large range, when the number of PDF pages is more than 2, unfortunately, this script cannot be used. So, please be careful about this.
And also, in this case, Javascript is used on a dialog. So, when you use this sample script, it is required to open the Spreadsheet and select the cells and run the script.
Note:
In your showing script, in order to use a created PDF data with PDF.js, the Spreadsheet is required to be publicly shared. But, in the case of PDF.js, it seems that the data URL can be directly used. So in this sample script, the created PDF is used as the data URL (base64). By this, it is not required to publicly share the Spreadsheet.
References:
PDF.js
CropImageByBorder_js

p5.js Í How do I play first N frames as images in a loop?

In the code below I want to:
save the first 5 seconds of the camera capture as frames
then each time round the draw() loop I want to draw the 1st frame on the canvas, then the 2nd one on the next draw loop, etc. until I reach the end and start back from the top.
However, this is not working and I believe it's because the imageData of each frame is an data:image/octet-stream;base64,.... String which I'm not sure how to draw on the canvas.
const FRAME_RATE = 10
const CAPTURE_DURATION = 5 // secs
let framesCaptured = []
let i = 0
function setup() {
frameRate(FRAME_RATE)
let video = createCapture(VIDEO)
video.hide()
createCanvas(640, 480)
saveFrames('frames', 'png', CAPTURE_DURATION, FRAME_RATE, (frames) => {
framesCaptured = frames.map(({ imageData }) => {
return imageData
})
})
}
function draw() {
if (i < framesCaptured.length) {
image(loadImage(framesCaptured[i]), 0, 0)
i = i === framesCaptured.length - 1 ? 0 : i+1
}
}
Btw, it's important that I have access to and loop through individual frame-images, because I will later be sending those to the server.
LoadImage can handle base64 encoded images, but you have to add "data:image/png;base64," in front of the string.
you could try loadImage("data:image/png;base64,"+framesCaptured[i])
( https://p5js.org/reference/#/p5/loadImage )

Export SVG to PDF with groups/layers intact

I have an SVG object that looks like this:
Each of the inner <g> elements have <path>s in them.
I want to export this SVG to PDF so the groups translate to layers (OCGs), like this:
<ThroughCut>
<Path>
<Path>
<Path>
<Path>
<Graphics>
<Path>
<Path>
<Path>
<Path>
Yet any tool I have tried for this puts all objects in the same layer, and basically throws away information about groups.
Solutions in JavaScript or Python are preferred, but anything that executes from the command line on a UNIX machine will do.
I solved my problem as stated here, by following this PyMuPDF issue on Github.
Since I have control over the input SVG, I managed to solve the problem by parsing two SVGs to PDFs and combining them in separate layers of a new document. This is what I'm doing:
import fitz
from svglib.svglib import svg2rlg
from reportlab.graphics.renderPDF import drawToString
def svg_to_doc(path):
"""Using this function rather than `fitz`' `convertToPDF` because the latter
fills every shape with black for some reason.
"""
drawing = svg2rlg(path)
pdfbytes = drawToString(drawing)
return fitz.open("pdf", pdfbytes)
# Create a new blank document
doc = fitz.open()
page = doc.new_page()
# Create "Layer1" and "Layer2" OCGs and get their `xref`s
xref_1 = doc.add_ocg('Layer1', on=True)
xref_2 = doc.add_ocg('Layer2', on=True)
# Load "layer_1" and "layer_2" svgs and convert to pdf
doc_1 = svg_to_doc("my_layer_1.svg")
doc_2 = svg_to_doc("my_layer_2.svg")
# Set the `page` dimensions. Note: for me it makes sense to set the bounding
# box of the output to the same as `doc_1`, because I know `doc_1` contains
# `doc_2`. If that were not the case, I would set `bb` to be a new
# `fits.Rect` object that contained both `doc_1` and `doc_2`.
bb = doc_1[0].rect
page.setMediaBox(bb)
# Put the docs in their respective OCGs
page.show_pdf_page(bb, doc_1, 0, oc=xref_1)
page.show_pdf_page(bb, doc_2, 0, oc=xref_2)
# Save
doc.save("output.pdf")
If I load "output.pdf" in Adobe Acrobat the layers show. Curiously, the same is not the case for Adobe Illustrator (here they are simply "Clip Groups"). Regardless, I believe this solves the problem as stated above.
my_layer_1.svg
my_layer_2.svg
My other solution, although correct, does not produce a PDF that is compatible with Adobe standards (for example, Illustrator will not see the OCGs as legitimate layers—although strangely, Acrobat will).
In case one needs to produce a PDF that is compatible with Adobe standards, and will be loaded correctly in Illustrator, another option is to use the Illustrator scripting API.
Here's a script that one can use to convert a loaded SVG file into a PDF with the desired layer structure.
/** Convert an open file in Illustrator to PDF, after removing the first layer.
* Useful for converting SVGs into PDFs, where it is desired that the first level
* `<g>` elements are converted to layers/OCGs in the exported PDF.
*/
// Select export destination
const destFolder = Folder.selectDialog( 'Select folder for PDF files.', '~' );
// Get the PDF options to be used
const options = getOptions();
// The SVG should have a single `Layer1` top layer...
const doc = app.activeDocument;
if (doc.layers.length == 1) {
// ... remove it
removeFirstLayer(doc)
// Create a file pointer for export...
var targetFile = getTargetFile(doc.name, '.pdf', destFolder);
// ... and save save `doc` in the file pointer.
doc.saveAs(targetFile, options);
}
/* --------- */
/* Utilities */
/* --------- */
function getOptions() {
// Create PDFSaveOptions object
var pdfSaveOpts = new PDFSaveOptions();
// Set PDFSaveOptions properties (toggle these comment/uncomment)
pdfSaveOpts.acrobatLayers = true;
pdfSaveOpts.colorBars = true;
pdfSaveOpts.colorCompression = CompressionQuality.AUTOMATICJPEGHIGH;
pdfSaveOpts.compressArt = true; //default
pdfSaveOpts.embedICCProfile = true;
pdfSaveOpts.enablePlainText = true;
pdfSaveOpts.generateThumbnails = true; // default
pdfSaveOpts.optimization = true;
pdfSaveOpts.pageInformation = true;
// pdfSaveOpts.viewAfterSaving = true;
return pdfSaveOpts;
}
function removeFirstLayer(doc) {
// Get the layer to be removed
var firstLayer = doc.layers[0];
// Convert groups into new layers
for (var i=firstLayer.groupItems.length-1; i>=0; i--) {
var group = firstLayer.groupItems[i];
var newLayer = firstLayer.layers.add();
newLayer.name = group.name;
for (var j=group.pageItems.length-1; j>=0; j--)
group.pageItems[j].move(newLayer, ElementPlacement.PLACEATBEGINNING);
}
// Move new layers to the document and remove `firstLayer`
for (var i=firstLayer.layers.length-1; i>=0; i--)
firstLayer.layers[i].move(firstLayer.parent, ElementPlacement.PLACEATBEGINNING);
firstLayer.remove();
}
function getTargetFile(docName, ext, destFolder) {
var newName = "";
// Add extension is none exists
if (docName.indexOf('.') < 0)
newName = docName + ext;
else
newName += docName.substring(0, docName.lastIndexOf('.')) + ext;
// Create file pointer
var myFile = new File(destFolder + '/' + newName);
// Check that file permissions are granted
if (myFile.open("w"))
myFile.close();
else
throw new Error('Access is denied');
return myFile;
}
Put the script in a file that ends with .jsx, and place in inside your Scripts folder in Illustrator. Mine is located at /Applications/Adobe Illustrator 2021/Presets/en_US/Scripts/svgToPDF.jsx.
Restart Illustrator
Execute the script from the File > Scripts > svgToPDF menu item.
Drawbacks
Illustrator costs money.
You have to manually execute the SVG -> PDF conversion. Could be automated with AppleScript, but it's really not something you want to have running on a server.

Resize and crop image (photoshop script)

I'm trying to resize and crop several images from a folder. First of all, let's see some parts of the script:
// DOCUMENT SETTINGS
app.preferences.rulerUnits = Units.MM;
app.displayDialogs = DialogModes.NO;
// FUNCTIONS
function processing_f_alta(folder, files, w, h) {
var f_alta = new Folder(folder + "/ALTA");
if ( ! f_alta.exists ) { f_alta.create(); }
for ( var cont = 0; cont < files.length; cont++ ) {
files[cont].copy(decodeURI(f_alta) + "/" + files[cont].displayName);
}
var files = f_alta.getFiles("*.tif");
for ( var cont = 0; cont < files.length; cont++ ) {
var img_file = app.open(files[cont]);
img_file.resizeImage(UnitValue(w, "cm"), UnitValue(h, "cm"), null, ResampleMethod.BICUBIC);
img_file.resizeCanvas(UnitValue(w, "cm"), UnitValue(h, "cm"), AnchorPosition.MIDDLECENTER);
img_file.close(SaveOptions.SAVECHANGES);
}
}
var w =prompt("Width (cm)","","Introduzca valor");
var h =prompt("Height (cm)","","Introduzca valor");
var f_origin_folder = Folder.selectDialog("Select the containing folder of the images");
var folder = new Folder(f_origin_folder);
var files = folder.getFiles("*.tif");
processing_f_alta(folder, files, w/2, h/2);
The script has much more code, but it's irrelevant.
The idea is to get an hipothetic width ("w") and height ("h") from the keyboard and get the folder when the images are ("folder"). So, the script gets all the ".tif" files of this folder and saves them into the variable "files".
the function processing_f_alta() is called with several params (folder, files, w/2, h/2). Why the last params are divided by 2 is irrelevant.
Into the function, the script creates a new folder into the "folder" called "ALTA" ant all the ".tif" files are copied into it. Then, the script gets all these last ".tif" files and resizes them to the new vales of with (w/2) and height (h/2).
EVERYTHING IS OK UNTIL HERE.
Now comes the problem. I want to crop the file with no distorsion but I don't know how to do it.
Let's see a real example (the example that I'm testing).
I've got an image of 40x40cm in a folder called "test". I execute the script with these values: w=30, h=15, folder="test".
When I run the script I get a new folder into "test" called "ALTA" with an image resized of 15x7,5cm. THAT'S CORRECT. But when I open the file, it's not been croped. It's been deformed vertically. What I wanted to get is this result but with the image cropped vertically, and I get an image deformed.
I've tryed crop(), resizeCanvas() functions, but I am not able to get the result that I'm expecting.
Could you help me to solve my problem.
Thanks in advance for your time.
Now that works:
// resizeImage([width] [, height] [, resolution] [, sampleMethod] [, amount]);
img_file.resizeImage(UnitValue(w, "cm"), null, null, ResampleMethod.BICUBIC);
// crop(bounds [, angle] [, width] [, height]);
// bounds = array[left, top, right, bottom]
bounds = [
0,
0,
w*10,
h*10
];
img_file.crop(bounds);
The next step will be cropping from the center of the image (now it does from the left-top point).
PD: I've done w*10 and h*10 because if original w=30 and h=30, for example, it crops the image to w->3 and h->3.
Try:
img_file.resizeImage(null, UnitValue(h, "cm"), null, ResampleMethod.BICUBIC);
if(img_file.width < w){
img_file.resizeImage(UnitValue(w, "cm"), null, null, ResampleMethod.BICUBIC);
}
(also: I don't have Photoshop on this machine so this is untested code, but basically you need to adjust the height first and then enlarge the width if it is smaller than what you want, before cropping the image)

JSFL - Batch export PNG at different sizes

I'm using Flash CS6 and I need to save a 32 bit PNG from a vector graphic in 9 different sizes.
16
32
36
48
72
114
128
150
480
How to write a batch export script for that in JSFL?
JSFL Docs (PDF)
I have a script that does what you are looking to do. It doesn't appear that you have really attempted to write any code or show any research attempt so if you do end up using this script I would appreciate the credit.
Select a movie clip on the stage then run this command.
Andrew Doll - Multiple Size PNG Exporter
Note: Before running this script export one PNG image using the desired PNG export settings.
fl.getDocumentDOM.exportPNG() accepts 3 paramaters. The first is the string for the file name. The second is a Boolean value that specifies whether to use the current PNG publish settings (true) or to display the Export PNG dialog box (false). The third is a Boolean value that specifies whether to export only the current frame (true) or to export all frames, with each frame as a separate PNG file (false).
Since this script sets the second paramater to true just be sure that the PNG export settings are already set to 32 bit PNG.
// Multiple Size PNG Exporter
// Copyright © 2014 Andrew Doll
// http://www.andrewdollanimation.com/
/* NOTE:Before running this script export one PNG image using the desired PNG export settings. fl.getDocumentDOM.exportPNG() accepts 3
** paramaters. The first is the string for the file name. The second is a Boolean value that specifies whether to use the current PNG
** publish settings (true) or to display the Export PNG dialog box (false). The third is a Boolean value that specifies whether to export
** only the current frame (true) or to export all frames, with each frame as a separate PNG file (false). Since this script sets the
** second paramater to true just be sure that the PNG export settings are already set to 32 bit PNG.
*/
// Check to see if there is a file open first.
var dom = fl.getDocumentDOM();
if (dom == null)
{
alert("Please open a file.");
}
else
{
var sel = [];
var exportSizeArray = [];
var folderURI = "";
var folderLocation = "";
var pngFileName = "";
var URI = "";
var selWidth;
var selHeight;
var sideToUse;
var scaleAmount;
function setupExportFolder()
{
// Create a folder and file name for the PNG files.
folderLocation = fl.browseForFolderURL("Select a folder.");
if(folderLocation != null)
{
folderURI = folderLocation + "/PNG Exports";
FLfile.createFolder(folderURI);
pngFileName = prompt("What would you like to name the png files?");
}
}
// Check if a movie clip on the stage is selected to export PNG images.
var selectionCheck = dom.selection;
if(!selectionCheck || !selectionCheck.length)
{
alert("Please select a movie clip on the stage.");
}
else
{
// Set up export sizes in this array.
exportSizeArray = [16, 32, 64, 128, 256, 512, 1024];
// Setup export folder
setupExportFolder();
if(folderLocation != null && pngFileName != null)
{
// Copy the selected artwork from the stage.
sel = dom.selection[0];
dom.clipCopy();
// Calculate the amount to scale the symbol by based on the longest side.
function calculateScaleAmount(selWidth, selHeight)
{
if(selWidth >= selHeight)
{
sideToUse = selWidth;
}
else
{
sideToUse = selHeight;
}
scaleAmount = exportSizeArray[i]/sideToUse;
return scaleAmount;
}
// Set the width and height of the symbol. Handle this with the size array.
for (var i = 0; i < exportSizeArray.length; i++)
{
// Create a new FLA document.
fl.createDocument();
dom = fl.getDocumentDOM();
// Resize the document to the current export size.
dom.width = exportSizeArray[i];
dom.height = exportSizeArray[i];
// Paste the artwork to the stage.
dom.clipPaste(true);
sel = dom.selection[0];
dom.setAlignToDocument(true);
selWidth = sel.width;
selHeight = sel.height;
calculateScaleAmount(selWidth, selHeight);
// Scale the artwork to the size of the stage based on the largest side.
dom.scaleSelection(scaleAmount, scaleAmount, "center");
// Align to the center of the stage.
dom.align("vertical center", true);
dom.align("horizontal center", true);
// Output the image.
URI = folderURI + "/" + pngFileName + "_" + exportSizeArray[i] + " x " + exportSizeArray[i] + "_";
dom.exportPNG(URI, true, true);
// Close the temporary FLA without saving.
dom.close(false);
}
}
}
}

Categories

Resources