Skip to content

Instantly share code, notes, and snippets.

@c3ry5
Last active January 10, 2019 16:08
Show Gist options
  • Save c3ry5/d76d25dead7d8dc260d325e8ef043798 to your computer and use it in GitHub Desktop.
Save c3ry5/d76d25dead7d8dc260d325e8ef043798 to your computer and use it in GitHub Desktop.
A script to export images in photoshop with max with and file size
//SaveforWebSP.jsx
var docRef = activeDocument;
var outputFolder = docRef.path;
var segments = app.activeDocument.name.split(".");
segments.splice(segments.length - 1, 1);
var docName = segments.join(".");
var fileName = prompt("Please Enter a file name without extension?", docName);
var safeFileName = fileName.replace(/[^A-Z0-9]+/ig, "_");
var fileExt = prompt("Please Enter a file name without extension?", "jpg");
if (safeFileName.length > 0) {
var NewfileRef = new File(outputFolder + "/" + safeFileName + "_aem." + fileExt);
var w = 2000; // new file width
var MaxSz = 500000; // max. 500Kb
var Qlt = 100; // initial quality 100
var x = 10; // decreasing step
// resize the image to the right width
docRef.resizeImage(UnitValue(w, "px"), null, 100, ResampleMethod.BICUBICSHARPER);
// Perform the first SaveForWeb Operation
ExpWeb(NewfileRef, Qlt);
// Keep trying to save the file with max. Qlt, but under MaxSz
while (NewfileRef.length > MaxSz) {
Qlt = Qlt - x;
NewfileRef = new File(NewfileRef);
NewfileRef.remove();
ExpWeb(NewfileRef, Qlt); // Perform a new SaveForWeb Operation, with slightly lower Qlt
if (Qlt <= 0) {
alert("The file can't be saved with the desired size AND quality.");
break // break the loop whenever the quality is as low as 50 (this shouldn't need to happen)
}
}
var FileSz = NewfileRef.length / 1024;
FileSz = Math.round(FileSz);
// close the original file without saving
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
} else {
alert("Please try again with a file name");
}
// SaveForWeb Export, with the desired constraints and parameters
function ExpWeb(FileNm, Qlt, type) {
var options = new ExportOptionsSaveForWeb();
options.quality = Qlt; // Start with highest quality (biggest file).
if (type = "png") {
options.format = SaveDocumentType.PNG; // Save Format for the file
} else {
options.format = SaveDocumentType.JPEG; // Save Format for the file
}
docRef.exportDocument(File(FileNm), ExportType.SAVEFORWEB, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment