2

I have a folder with a lot of subfolders, each with a bunch of TIFs and PSD files inside. Some of these have transparency in them while some don't. These files vary massively in size.

I need all the files to be turned into JPGs, or if they contain transparency, PNGs. I require the files to be 200kb or less and don't really mind how large they are as long as they aren't scaled up.

Someone on a forum (who I'm insanely thankful for) wrote a fair bit of code for it, which my friend modified to suit exactly what I was asking and we're nearly there now.

It worked fine, the only problem being that a lot of images came out 1x1 pixel and a solid block of colour.

We've found this was consistently happening with the same images for some reason, but couldn't work out what exactly it was in these images.

Now Mr forum blokey ( http://www.photoshopgurus.com/forum/members/paul-mr.html ) modified the script and it now seems to work fine with PSDs.

It's working with TIFs with transparency but some of the TIFs with 100% opacity it just won't work on. I can't find much that's consistent with these files other than the colour blue, though this just could be a massive coincidence and probably is (there's a lot of blue in the images I've been dealing with).

Below is a link to the thread in which the code was first written. Paul MR seems to think the colorsampler bit is a little suspect so perhaps that's what's causing the problems (blueness?).

http://www.photoshopgurus.com/forum/photoshop-actions-automation/34745-batching-tiffs-jpg-png-w-automatic-resize-based-filesize.html

I wish I could do a little more to try and work this out myself but I've barely a speck of understanding on this stuff, I just know when there's a situation where a bit of scripting could help out.

Below is the script as it currently stands:

#target PhotoshopString.prototype.endsWith  = function(str) {
 return (this.match(str  + "$")  == str)
} String.prototype.startsWith  = function(str) {
    return this.indexOf(str)  == 0;
};
var desiredFileSize  = 200000;
app.bringToFront();
app.displayDialogs  = DialogModes.NO;
main();
//app.displayDialogs = DialogModes.YES;
function main() {
    var topLevelFolder  = Folder.selectDialog("Please select top level folder.");
    if (topLevelFolder  == null)return;
    var FileList  = [];
    getFileList(topLevelFolder);
    var startRulerUnits  = app.preferences.rulerUnits;
    app.preferences.rulerUnits  = Units.PIXELS;
    for (var f in FileList)  {
        app.open(FileList[f]);
        activeDocument.changeMode(ChangeMode.RGB);
        try  {
            activeDocument.mergeVisibleLayers();
        } catch(e)  {} var Name  = decodeURI(app.activeDocument.name).replace(/.[^.] + $ /, '');
        if (hasTransparency(FileList[f]))  {
            var saveFile  = File(FileList[f].path  + "/"  + Name  + ".png");
            SavePNG(saveFile);
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
        } else  {
            var saveFile  = File(FileList[f].path  + "/"  + Name  + ".jpg");
            SaveForWeb(saveFile, 80);
            app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
        } app.preferences.rulerUnits  = startRulerUnits;
    } function getFileList(folder)  {
        var fileList  = folder.getFiles();
        for (var i = 0; i < fileList.length; i++)  {
            var file  = fileList[i];
            if (file instanceof Folder)  {
                getFileList(file);
            } else  {
                if ((file.name.endsWith("tiff")  || file.name.endsWith("tif")  || file.name.endsWith("psd"))  &&  ! file.name.startsWith("._"))FileList.push(file);
            }
        }
    } alert(FileList.length  + " files have been modified.");
} function hasTransparency(file) {
    if (file.name.endsWith("tiff")  || file.name.endsWith("tif"))  {
        var sample  = app.activeDocument.colorSamplers.add([new UnitValue(1.5, 'px'), new UnitValue(1.5, 'px')]);
        try  {
            sample.color.rgb.hexValue;
            sample.remove();
            return false;
        } catch(e)  {
            sample.remove();
            return true;
        }
    } var doc  = activeDocument;
    if (doc.activeLayer.isBackgroundLayer)return false;
    var desc  = new ActionDescriptor();
    var ref  = new ActionReference();
    ref.putProperty(charIDToTypeID("Chnl"), charIDToTypeID("fsel"));
    desc.putReference(charIDToTypeID("null"), ref);
    var ref1  = new ActionReference();
    ref1.putEnumerated(charIDToTypeID("Chnl"), charIDToTypeID("Chnl"), charIDToTypeID("Trsp"));
    desc.putReference(charIDToTypeID("T "), ref1);
    executeAction(charIDToTypeID("setd"), desc, DialogModes.NO);
    var w  = doc.width.as('px');
    var h  = doc.height.as('px');
    var transChannel  = doc.channels.add();
    doc.selection.store(transChannel);
    if (transChannel.histogram[255]  != (h  * w))  {
        transChannel.remove();
        return true;
    } else  {
        transChannel.remove();
        return false;
    }
};
function SavePNG(saveFile) {
    pngSaveOptions  = new PNGSaveOptions();
    activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
    var actualFilesize  = saveFile.length;
    var ratio  = desiredFileSize / actualFilesize;
    if (ratio  < 1)  {
        var imageScale  = Math.sqrt(ratio);
        activeDocument.resizeImage(activeDocument.width  * imageScale, activeDocument.height  * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
        activeDocument.saveAs(saveFile, pngSaveOptions, true, Extension.LOWERCASE);
    }
}
function SaveForWeb(saveFile, jpegQuality) {
    var sfwOptions  = new ExportOptionsSaveForWeb();
    sfwOptions.format  = SaveDocumentType.JPEG;
    sfwOptions.includeProfile  = false;
    sfwOptions.interlaced  = 0;
    sfwOptions.optimized  = true;
    sfwOptions.quality  = jpegQuality;
    activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
    var actualFilesize  = saveFile.length;
    var ratio  = desiredFileSize / actualFilesize;
    if (ratio  < 1)  {
        var imageScale  = Math.sqrt(ratio);
        activeDocument.resizeImage(activeDocument.width  * imageScale, activeDocument.height  * imageScale, activeDocument.resolution, ResampleMethod.BICUBICSMOOTHER);
        activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);
    }
}
Breakwhore
  • 21
  • 1
  • 3
  • If you have it working for PSDs, you could just use imagemagick for the tifs. Something like `mogrify -format png *.tif` would work. – Dagg Nabbit Dec 18 '11 at 19:32
  • That won't work for filesize though will it? http://www.imagemagick.org/discourse-server/viewtopic.php?f=5&t=10121 – Breakwhore Dec 18 '11 at 20:16
  • well, png and jpeg both compress, tiff does not. So file size should be taken care of. Depending on what your images look like, you may be able to convert the pngs to indexed using `pngquant`; the color depth and size will both be reduced. Or, if color depth must be retained, you can try using `pngcrush` afterward to squeeze a bit more out of it. Jpgs have the normal jpg lossy compression. – Dagg Nabbit Dec 18 '11 at 21:39
  • Everything massively varies in size though so won't I be having still to be doing a series of steps? All my files either begin being TIF or PSD. I might not be understanding, sorry. I have no idea which files will have transparency in them and which won't, hence the need for the script. – Breakwhore Dec 18 '11 at 22:00
  • I would just convert everything to png, unless you have an easy way of identifying some of the images as *photographic* images (in which case you should use jpeg for those). Transparency probably shouldn't be the deciding factor between png/jpeg; rather it should be jpg for photographic and png for non-photographic images. If you can't sort them out, you might as well just convert everything to png. – Dagg Nabbit Dec 18 '11 at 22:17
  • Interesting, so turn everything into PNG and then make them a smaller file size with pngquant? I'm having trouble using that as it's taking so long to make my files smaller and I'm on a real time limit. My images sometimes do have some major colour depth as they're from computer games. – Breakwhore Dec 18 '11 at 22:35
  • Plus I have tens of thousands to be dealing with in various subfolders. – Breakwhore Dec 18 '11 at 22:36
  • how small do they need to be? Just as small as possible, or some specific size? In other words, can you just tell bossman "welp, i got them as small as possible" and call it a day, or is there a specific requirement? – Dagg Nabbit Dec 18 '11 at 22:37

0 Answers0