Collection of some useful photoshop code snippets, functions and etc…
Color Fill to Shape Layer
1 2 3 4 5 6 7 |
// Fill Color if Layer is a Shape Layer function Color_Fill_Shape_Layer(r,g,b) { var desc1 = new ActionDescriptor(); var ref1 = new ActionReference(); ref1.putEnumerated(sTID("contentLayer"), cTID('Ordn'), cTID('Trgt')); desc1.putReference(cTID('null'), ref1); var desc2 = new ActionDescriptor(); var desc3 = new ActionDescriptor(); desc3.putDouble(cTID('Rd '), r); desc3.putDouble(cTID('Grn '), g); desc3.putDouble(cTID('Bl '), b); desc2.putObject(cTID('Clr '), sTID("RGBColor"), desc3); desc1.putObject(cTID('T '), sTID("solidColorLayer"), desc2); executeAction(cTID('setd'), desc1, DialogModes.NO); }; |
Center Layer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
#target photoshop var doc = app.activeDocument; var layer = activeDocument.activeLayer; _restoreLayer = true function wrapLCLayer (doc, layer, ftn) { var ad = app.activeDocument; if (doc) { if (ad != doc) { app.activeDocument = doc; } } else { doc = ad; } var al = doc.activeLayer; var alvis = al.visible; if (layer && doc.activeLayer != layer) { doc.activeLayer = layer; } else { layer = doc.activeLayer; } var res = undefined; try { res = ftn(doc, layer); } finally { if (_restoreLayer) { if (doc.activeLayer != al) { doc.activeLayer = al; } if (!doc.activeLayer.isBackgroundLayer) { doc.activeLayer.visible = alvis; } } if (Stdlib._restoreDoc) { if (app.activeDocument != ad) { app.activeDocument = ad; } } } return res; }; function hasLayerMask (doc, layer) { function _ftn() { var ref = new ActionReference(); ref.putEnumerated(cTID("Lyr "), cTID("Ordn"), cTID("Trgt")); var desc = executeActionGet(ref); return desc.hasKey(cTID("UsrM")); } return wrapLCLayer(doc, layer, _ftn); }; function getLayerBounds (doc, layer) { var reenable = false; var st; if (hasLayerMask(doc, layer) && isLayerMaskEnabled(doc, layer)) { st = doc.activeHistoryState; disableLayerMask(doc, layer); reenable = true; } var lbnds = layer.bounds; // fix this to modify the history state if (reenable) { Stdlib.enableLayerMask(doc, layer); } for (var i = 0; i < 4; i++) { lbnds[i] = lbnds[i].value; } return lbnds; } function centerLayer(doc, layer) { var ru = app.preferences.rulerUnits; app.preferences.rulerUnits = Units.PIXELS; var bnds = getLayerBounds(doc, layer); var layerW = bnds[2]-bnds[0]; var layerH = bnds[3]-bnds[1]; var docW = doc.width.value; var docH = doc.height.value; var x = (docW/2) - (layerW/2); var y = (docH/2) - (layerH/2); var deltaX = x - bnds[0]; var deltaY = y - bnds[1]; layer.translate(deltaX, deltaY); } centerLayer (doc,layer); |
Clear Guides via Extendscript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#target photoshop cTID = function(s) { return app.charIDToTypeID(s); }; sTID = function(s) { return app.stringIDToTypeID(s); }; function clearguides () { var desc1 = new ActionDescriptor(); var ref1 = new ActionReference(); ref1.putEnumerated(cTID('Mn '), cTID('MnIt'), cTID('ClrG')); desc1.putReference(cTID('null'), ref1); executeAction(cTID('slct'), desc1, DialogModes.NO); }; clearguides (); |
Run any menu item using doMenuItem command
1 2 3 4 5 6 7 |
cTID = function(s) { return app.charIDToTypeID(s); }; sTID = function(s) { return app.stringIDToTypeID(s); }; doMenuItem = function(item, interactive) { var ref = new ActionReference(); ref.putEnumerated(cTID("Mn "), cTID("MnIt"), item); var desc = new ActionDescriptor(); desc.putReference(cTID("null"), ref); try { var mode = (interactive != true ? DialogModes.NO : DialogModes.ALL); executeAction(sTID("select"), desc, mode); } catch (e) { if (!e.message.match("User cancelled")) { throw e; } else { return false; } } return true; } doMenuItem(cTID('ActP')); // Set Zoom to 100% |
Selecting Specific Tool
Sample usage;
1 |
setTool("paintbrushTool"); |
Replace”paintbrushTool” with the desired tool names below;
moveTool
marqueeRectTool
marqueeEllipTool
marqueeSingleRowTool
marqueeSingleColumnTool
lassoTool
polySelTool
magneticLassoTool
quickSelectTool
magicWandTool
cropTool
sliceTool
sliceSelectTool
spotHealingBrushTool
magicStampTool
patchSelection
redEyeTool
paintbrushTool
pencilTool
colorReplacementBrushTool
cloneStampTool
patternStampTool
historyBrushTool
artBrushTool
eraserTool
backgroundEraserTool
magicEraserTool
gradientTool
bucketTool
blurTool
sharpenTool
smudgeTool
dodgeTool
burnInTool
saturationTool
penTool
freeformPenTool
addKnotTool
deleteKnotTool
convertKnotTool
typeCreateOrEditTool
typeVerticalCreateOrEditTool
typeCreateMaskTool
typeVerticalCreateMaskTool
pathComponentSelectTool
directSelectTool
rectangleTool
roundedRectangleTool
ellipseTool
polygonTool
lineTool
customShapeTool
textAnnotTool
soundAnnotTool
eyedropperTool
colorSamplerTool
rulerTool
handTool
zoomTool
1 2 3 4 5 6 7 8 9 10 11 12 |
#target photoshop app.bringToFront(); function setTool(tool) { var desc9 = new ActionDescriptor(); var ref7 = new ActionReference(); ref7.putClass( app.stringIDToTypeID(tool) ); desc9.putReference( app.charIDToTypeID('null'), ref7 ); executeAction( app.charIDToTypeID('slct'), desc9, DialogModes.NO ); } setTool("paintbrushTool"); |
Remove All Empty Layer Groups – Extendscript Snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var doc = app.activeDocument; function removeallemptylayergroups(doc) { var foundEmpty = true; for( var i = doc.layerSets.length-1; 0 <= i; i--) { if( removeallemptylayergroups(doc.layerSets[i])) { doc.layerSets[i].remove(); } else { foundEmpty = false; } } if (doc.artLayers.length > 0) { foundEmpty = false; } return foundEmpty; } removeallemptylayergroups(doc); |
Remove All Invisible – Hidden Layers – Extendscript Snippet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var doc = app.activeDocument; function removevisiblelayers(doc) { for( var i = doc.artLayers.length-1; 0 <= i; i--) { try { if(!doc.artLayers[i].visible) { doc.artLayers[i].remove(); } } catch (e) { } } for( var i = doc.layerSets.length-1; 0 <= i; i--) { removevisiblelayers(doc.layerSets[i]); } } removevisiblelayers(doc); |
Copy to a New Layer Extendscript Snippet
1 2 3 |
var id14 = charIDToTypeID( "CpTL" ); executeAction( id14, undefined, DialogModes.NO ); var theCopiedLayer = app.activeDocument.activeLayer; |
Showing Color Picker in ExtendScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function colorpicker (result_color) { var hexToRGB = function(hex) { var r = hex >> 16; var g = hex >> 8 & 0xFF; var b = hex & 0xFF; return [r, g, b]; }; var color_decimal = $.colorPicker(); $.writeln(color_decimal); var color_hexadecimal = color_decimal.toString(16); $.writeln(color_hexadecimal); var color_rgb = hexToRGB(parseInt(color_hexadecimal, 16)); $.writeln(color_rgb); var result_color = [color_rgb[0] / 255, color_rgb[1] / 255, color_rgb[2] / 255]; $.writeln(result_color); return result_color; } alert (colorpicker();); |
History States & Snapshots Iteration
This script iterates through history states and snapshots in an active document and checks if any snapshot name matches with given string value; (Resulting boolean; true or false)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Photoshop Script by Mehmet Şensoy // Iterates through history states and snapshots,gives boolean result if snapshot name matches entered text. function checkhistorystates(snapshotavailable,nameofsnapshot) { var snapshotavailable = false; var doc = app.activeDocument; var theHist = doc.historyStates; var theSnaps = new Array; for (var m = 0; m < theHist.length; m++) { var theState = theHist[m]; if (theState.snapshot == true && theState.name == nameofsnapshot ) { snapshotavailable= true; return snapshotavailable; return nameofsnapshot; theSnaps.push(theState) } }; return snapshotavailable; } var snapshotstatus = checkhistorystates(false,'Initial'); if (snapshotstatus == true) { alert ("True"); } else if (snapshotstatus != true) { alert ("False"); } |
Remove History State – Snapshot with Name
1 2 3 4 5 6 7 8 9 |
// Remove Snapshot with Name // Usage : removesnapshot("nameofsnapshot"); function removesnapshot(name) { var desc = new ActionDescriptor(); var ref = new ActionReference(); ref.putName( charIDToTypeID('SnpS'), name ); desc.putReference( charIDToTypeID('null'), ref ); executeAction( charIDToTypeID('Dlt '), desc, DialogModes.NO ); } |
Working with Paths
Count number of paths in document
1 2 3 |
var doc=activeDocument; var pathcount =doc.pathItems.length; alert (pathcount); |
Count number of points in first sub path.
1 2 3 4 5 |
var doc=activeDocument; var firstpath=doc.pathItems[0]; // Assing Path firstpath.select(); // Select Path var pathpointcount = firstpath.subPathItems[0].pathPoints.length; alert (pathpointcount); |
More Details about sub paths and points count;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#target Photoshop main(); function main(){ if(!documents.length) return; try{ var Info = ''; var workPath = app.activeDocument.pathItems.getByName("Work Path"); for(var b =0;b<workPath.subPathItems.length;b++){ Info += "Sub Path "+b +" Closed = "+workPath.subPathItems[b].closed; Info +="\rSub Path "+b+" has " +workPath.subPathItems[b].pathPoints.length+ " Pathpoints"+"\r"; } alert(Info); }catch(e){alert("Unable to get path info");} } |
Adding a Simple Path
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#target photoshop // create the array of PathPointInfo objects var lineArray =new Array(); var doc=activeDocument; lineArray.push(new PathPointInfo()); lineArray[0].kind = PointKind.CORNERPOINT; lineArray[0].anchor = new Array(100, 100); // x,y lineArray[0].leftDirection = lineArray[0].anchor; lineArray[0].rightDirection = lineArray[0].anchor; lineArray.push(new PathPointInfo()); lineArray[1].kind = PointKind.CORNERPOINT; lineArray[1].anchor = new Array(100, 500); // x,y lineArray[1].leftDirection = lineArray[1].anchor; lineArray[1].rightDirection = lineArray[1].anchor; // create a SubPathInfo object, which holds the line array in its entireSubPath property. var lineSubPathArray = new Array(); lineSubPathArray.push(new SubPathInfo()); lineSubPathArray[0].operation = ShapeOperation.SHAPEXOR; lineSubPathArray[0].closed = false; lineSubPathArray[0].entireSubPath = lineArray; //create the path item, passing subpath to add method var myPathItem = doc.pathItems.add("A Line", lineSubPathArray); // stroke it so we can see something myPathItem.strokePath(ToolType.BRUSH); |
Draw Shape
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/* Code by Mike Hale http://www.ps-scripts.com/bb/viewtopic.php?f=14&t=1802&start=15 with small modification by Vladimir Carrer */ function DrawShape() { var doc = app.activeDocument; var y = arguments.length; var i = 0; var lineArray = []; for (i = 0; i < y; i++) { lineArray[i] = new PathPointInfo; lineArray[i].kind = PointKind.CORNERPOINT; lineArray[i].anchor = arguments[i]; lineArray[i].leftDirection = lineArray[i].anchor; lineArray[i].rightDirection = lineArray[i].anchor; } var lineSubPathArray = new SubPathInfo(); lineSubPathArray.closed = true; lineSubPathArray.operation = ShapeOperation.SHAPEADD; lineSubPathArray.entireSubPath = lineArray; var myPathItem = doc.pathItems.add("myPath", [lineSubPathArray]); var desc88 = new ActionDescriptor(); var ref60 = new ActionReference(); ref60.putClass(stringIDToTypeID("contentLayer")); desc88.putReference(charIDToTypeID("null"), ref60); var desc89 = new ActionDescriptor(); var desc90 = new ActionDescriptor(); var desc91 = new ActionDescriptor(); desc91.putDouble(charIDToTypeID("Rd "), 0.000000); // R desc91.putDouble(charIDToTypeID("Grn "), 0.000000); // G desc91.putDouble(charIDToTypeID("Bl "), 0.000000); // B var id481 = charIDToTypeID("RGBC"); desc90.putObject(charIDToTypeID("Clr "), id481, desc91); desc89.putObject(charIDToTypeID("Type"), stringIDToTypeID("solidColorLayer"), desc90); desc88.putObject(charIDToTypeID("Usng"), stringIDToTypeID("contentLayer"), desc89); executeAction(charIDToTypeID("Mk "), desc88, DialogModes.NO); myPathItem.remove(); } // X,Y // Put the coordinates in clockwise order DrawShape([100, 100], [100, 200], [200, 200], [200, 100]); |
Sorting Layers in an Alphabetical Order
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
function sortLayerAZ (layerList) { var layers; // check if layer list is provided if (layerList) { layers = layerList; } else { layers = activeDocument.layers; } var len = layers.length; if (len > 1) { var layersArray = []; // store all layers in an array for (var i = 0; i < len; i++) { layersArray.push(layers[i]); } // remove Background layer from array var o = layersArray.length; while(o--) { if(layersArray[o].hasOwnProperty('name') && layersArray[o].name === 'Background' ) { layersArray.splice(o,1); } } // sort layer top to bottom layersArray.sort(); for (i = 0; i < layersArray.length-1; i++) { layersArray[i].move(layers[i], ElementPlacement.PLACEBEFORE); } } } |
Create History Snapshot Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#target photoshop cTID = function(s) { return app.charIDToTypeID(s); }; sTID = function(s) { return app.stringIDToTypeID(s); }; // Create History Snapshot function HistoryState(enabled, withDialog,nameofsnapshot) { if (enabled != undefined && !enabled) return; var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO); var desc1 = new ActionDescriptor(); var ref1 = new ActionReference(); ref1.putClass(cTID('SnpS')); desc1.putReference(cTID('null'), ref1); var ref2 = new ActionReference(); ref2.putProperty(cTID('HstS'), cTID('CrnH')); desc1.putReference(cTID('From'), ref2); desc1.putString(cTID('Nm '), nameofsnapshot); desc1.putEnumerated(cTID('Usng'), cTID('HstS'), cTID('FllD')); executeAction(cTID('Mk '), desc1, dialogMode); }; // Usage : HistoryState(1,0,"NameofSnapshot"); |
Merge Visible Layers
1 2 3 |
try{ activeDocument.mergeVisibleLayers(); }catch(e){} |
Finding Layer Count;
1 2 |
var layerNum = app.activeDocument.layers.length; alert("Layers Number : " + layerNum, 'Total Layer Count'); |
Add Prefix to Selected Layers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
#target photoshop; app.bringToFront(); if(documents.length){ var prefix = "Prefix_" var selLayers = getSelectedLayersIdx(); for (var a in selLayers){ selectLayerByIndex(selLayers[a]); activeDocument.activeLayer.name = prefix + activeDocument.activeLayer.name; } } function selectLayerByIndex(index,add){ var ref = new ActionReference(); ref.putIndex(charIDToTypeID("Lyr "), index); var desc = new ActionDescriptor(); desc.putReference(charIDToTypeID("null"), ref ); if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) ); desc.putBoolean( charIDToTypeID( "MkVs" ), false ); try{ executeAction(charIDToTypeID("slct"), desc, DialogModes.NO ); }catch(e){} }; function getSelectedLayersIdx(){ var selectedLayers = new Array; var ref = new ActionReference(); ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); var desc = executeActionGet(ref); if( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){ desc = desc.getList( stringIDToTypeID( 'targetLayers' )); var c = desc.count var selectedLayers = new Array(); for(var i=0;i<c;i++){ try{ activeDocument.backgroundLayer; selectedLayers.push( desc.getReference( i ).getIndex() ); }catch(e){ selectedLayers.push( desc.getReference( i ).getIndex()+1 ); } } }else{ var ref = new ActionReference(); ref.putProperty( charIDToTypeID("Prpr") , charIDToTypeID( "ItmI" )); ref.putEnumerated( charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); try{ activeDocument.backgroundLayer; selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( "ItmI" ))-1); }catch(e){ selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( "ItmI" ))); } var vis = app.activeDocument.activeLayer.visible; if(vis == true) app.activeDocument.activeLayer.visible = false; var desc9 = new ActionDescriptor(); var list9 = new ActionList(); var ref9 = new ActionReference(); ref9.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') ); list9.putReference( ref9 ); desc9.putList( charIDToTypeID('null'), list9 ); executeAction( charIDToTypeID('Shw '), desc9, DialogModes.NO ); if(app.activeDocument.activeLayer.visible == false) selectedLayers.shift(); app.activeDocument.activeLayer.visible = vis; } return selectedLayers; }; |
Activate all layer(s) containing given characters.
(In this example; Row)
Replace the word ‘Row’. (Between //)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
// This Script makes active of all layers including specific characters in their layer names. // Script is originally written by JJMack. Slight modifications has been made. #target photoshop cTID = function(s) { return app.charIDToTypeID(s); }; sTID = function(s) { return app.stringIDToTypeID(s); }; var re = /Row/;// -- Write between / / your string... var matches = collectNamesAM(re);// get array of matching layer indexes for( var l = 0; l < matches.length; l++ ){ makeActiveByIndex( matches[l], true ); }// next match if any function collectNamesAM(re){ var allLayers = new Array(); var startLoop = Number( !hasBackground() ); var endLoop = getNumberOfLayer(); for( var l = startLoop;l < endLoop; l++){ while( !isValidActiveLayer( l ) ) { l++; } if( getLayerNameByIndex( l ).match(re) != null){ allLayers.push( l ); } } return allLayers; }; function getActiveLayerIndex() { var ref = new ActionReference(); ref.putProperty( 1349677170 , 1232366921 ); ref.putEnumerated( 1283027488, 1332896878, 1416783732 ); var res = executeActionGet(ref).getInteger( 1232366921 ) - Number( hasBackground() ); res == 4 ? res++:res// why the skip in this doc? return res; } function isValidActiveLayer( idx ) { var propName = stringIDToTypeID( 'layerSection' );// can't replace var ref = new ActionReference(); ref.putProperty( 1349677170 , propName);// TypeID for "Prpr" // 'Lyr ", idx ref.putIndex( 1283027488, idx ); var desc = executeActionGet( ref ); var type = desc.getEnumerationValue( propName ); var res = typeIDToStringID( type ); return res == 'layerSectionEnd' ? false:true; }; function hasBackground(){ var res = undefined; try{ var ref = new ActionReference(); ref.putProperty( 1349677170 , 1315774496); ref.putIndex( 1283027488, 0 ); executeActionGet(ref).getString(1315774496 );; res = true; }catch(e){ res = false} return res; }; function makeActiveByIndex( idx, forceVisible ){ try{ var desc = new ActionDescriptor(); var ref = new ActionReference(); ref.putIndex(charIDToTypeID( "Lyr " ), idx) desc.putReference( charIDToTypeID( "null" ), ref ); desc.putEnumerated(sTID("selectionModifier"), sTID("selectionModifierType"), sTID("addToSelection")); desc.putBoolean( charIDToTypeID( "MkVs" ), forceVisible ); executeAction( charIDToTypeID( "slct" ), desc, DialogModes.NO ); }catch(e){ return -1;} }; function getNumberOfLayer(){ var ref = new ActionReference(); ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") ); var desc = executeActionGet(ref); var numberOfLayer = desc.getInteger(charIDToTypeID("NmbL")); return numberOfLayer; }; function getLayerNameByIndex( idx ) { var ref = new ActionReference(); ref.putProperty( charIDToTypeID("Prpr") , charIDToTypeID( "Nm " )); ref.putIndex( charIDToTypeID( "Lyr " ), idx ); return executeActionGet(ref).getString(charIDToTypeID( "Nm " ));; }; |
Create desired number of rows & columns and save them as png with prefix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#target photoshop if (documents.length != 1) { alert("Must open exactly one image in photoshop first"); } else { // Prompt user for number of columns and rows: var cols = parseInt(prompt("How many columns?", 4)); var rows = parseInt(prompt("How many rows?", 4)); var total = cols*rows; // Determine target tile size: var image = app.documents[0]; var tileWidth = image.width / cols; var tileHeight = image.height / rows; // Draw guides along cuts: for(col = 0; col <= cols; col++) { image.guides.add(Direction.VERTICAL, col * tileWidth); } for(row = 0; row <= rows; row++) { image.guides.add(Direction.HORIZONTAL, row * tileHeight); } // Prompt user to confirm, and for file prefix to save out to: var savePath = File.saveDialog("Save Image File Prefix", ""); if(!savePath) {alert("Cancelled"); exit;} if(!confirm("Create " + total + " tiles, each of " + tileWidth + " x " + tileHeight + "?\n\n\n" + "Tiles will be saved as '" + savePath.fsName + "1,1.png' '...1,2.png' etc")) { exit; } // For each tile: for(row = 0; row < rows; row++) { for(col = 0; col < cols; col++) { // Determine crop coordinates (in pixels): var top = row * tileHeight; var bottom = top + tileHeight; var left = col * tileWidth; var right = left + tileWidth; // Duplicate image, crop, save as PNG and close: var tile = image.duplicate(); // Duplicate file. cropCurrentDocument(top, left, bottom, right); saveTileAsPng(tile, savePath.fsName, col, row); tile.close(SaveOptions.DONOTSAVECHANGES); } } } function saveTileAsPng(img, origFilePath, col, row) { var newFilePath = origFilePath + "_" + col + "," + row + ".png"; var newFile = new File(newFilePath); var pngSaveOptions = new PNGSaveOptions(); activeDocument.saveAs(newFile, pngSaveOptions, true, Extension.LOWERCASE); } // Crops active document by a rectangle with the given pixel coordinages. function cropCurrentDocument(top, left, bottom, right){ app.preferences.rulerUnits = Units.PIXELS; activeDocument.selection.select( [[left, top], [right, top], [right, bottom], [left, bottom]], SelectionType.REPLACE, 0, false); executeAction(charIDToTypeID( "Crop" ), new ActionDescriptor(), DialogModes.NO ); } |
Leave a Reply
Want to join the discussion?Feel free to contribute!