Skip to content

Instantly share code, notes, and snippets.

Created September 17, 2013 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/95374b5e3db88261ce4c to your computer and use it in GitHub Desktop.
Save anonymous/95374b5e3db88261ce4c to your computer and use it in GitHub Desktop.
//Save an image with a size constraint in its original folder; if quality restriction is met, resize longest dimension until criteria are met
var docRef = activeDocument;
var outputFolder = docRef.path;
NamesaveRef = new File(outputFolder + "/WM");
var NewfileRef = new File(NamesaveRef);
// quality/size constraints
var h = 2400; //new file height
var w = 2400; // new file width
var MaxSz = 97280; // max. 85Kb
var MinSz = 288; // min. 4in @72dpi
var Qlt = 100; // initial quality 100
var x = 5; // decreasing step
var Px = 72; //decreasing step in px once Qlt < 50
// Perform the first SaveForWeb Operation
ExpWeb(NewfileRef, Qlt);
//Check to see if document is wider than taller. Else will shorten height instead.
if (activeDocument.width > activeDocument.height)
{
// 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 <= 50); {
while (NewfileRef.length > MaxSz) {
w = w - Px;
NewfileRef = new File(NewfileRef);
NewfileRef.remove();
NewfileRef.resizeImage(UnitValue(w,"px"),null,72,null);
if (w <= MinSz) {
alert("The file can't be saved with the desired size AND quality.");
break;
}
}
}
}
else {
// 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 <= 50); {
while (NewfileRef.length > MaxSz) {
h = h - Px;
NewfileRef = new File(NewfileRef);
NewfileRef.remove();
NewfileRef.resizeImage(UnitValue, null,(h,"px"),72,null);
if (h <= MinSz) {
alert("The file can't be saved with the desired size AND quality.");
break;
}
}
}
}
// close the original file without saving
activeDocument.close(SaveOptions.DONOTSAVECHANGES);
//docRef.resizeImage(UnitValue(w,"px"),null,72,null);
// SaveForWeb Export, with the desired constraints and parameters
function ExpWeb(FileNm, Qlt) {
var options = new ExportOptionsSaveForWeb();
options.quality = Qlt; // Start with highest quality (biggest file).
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