Search code examples
javascriptphotoshopphotoshop-script

Script for exporting GIF from Photoshop


I have the following function:

function saveLayerGIF(layer, lname, path, shouldMerge) {
    activeDocument.activeLayer = layer;
    dupLayers();
    if (shouldMerge === undefined || shouldMerge === true) {
        activeDocument.mergeVisibleLayers();
    }
    activeDocument.trim(TrimType.TRANSPARENT,true,true,true,true);
    var saveFile= File(path +"/assets/"+lname);
    SaveForWebGIF(saveFile);      
    app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}

This gives me the layer that I need and specifies certain things like where the exported file should be placed for example:

Now I have a different function which performs the task of going into the "Save for Web" menu and export a GIF with the set parameters:

function SaveForWebGIF(saveFile) {  
var sfwOptions = new ExportOptionsSaveForWeb();   
   sfwOptions.format = SaveDocumentType.COMPUSERVEGIF;
   sfwOptions.transparency = 1;  
   sfwOptions.includeProfile = false;   
   sfwOptions.interlaced = 1;   
   sfwOptions.optimized = true;
   sfwOptions.ColorReductionType = ColorReductionType.SELECTIVE;
   sfwOptions.dither = Dither.NONE;  
   sfwOptions.ditherAmount = 80;
   sfwOptions.webSnap = 0;
   sfwOptions.colors = 128; 
activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions);  
}

The images gets exported correctly and is in a gif format. It also has both of the frames which are in the gif image, but they are just put on top of each other and no animation is happening.

How can i programmatically export a gif image? Do I need to first loop over the frames from the timeline and somehow combine them before I run the export? the gif is set to loop forever.


Solution

  • This is guess... but I think you haven't changed the layers to frames. Try this before your export code:

    // create frame animation
    var idmakeFrameAnimation = stringIDToTypeID( "makeFrameAnimation" );
    executeAction( idmakeFrameAnimation, undefined, DialogModes.NO );
    // create animation from layers
    var idanimationFramesFromLayers = stringIDToTypeID( "animationFramesFromLayers" );
    var desc32 = new ActionDescriptor();
    executeAction( idanimationFramesFromLayers, desc32, DialogModes.NO );