javascript – Photoshop transparency trimming

javascript – Photoshop transparency trimming

For example:

  // save current preferences and make sure PS units are in pixels
  var startRulerUnits = preferences.rulerUnits
  preferences.rulerUnits = Units.PIXELS

  // initial variables
  var doc = activeDocument;
  var docW = doc.width;
  var docH = doc.height;
  var al = doc.activeLayer;
  // bounds is an array of [left, top, right, bottom] 
  // coordinates from the top left corner
  var bounds = al.bounds; 
  // distances from each side of the document
  var left = bounds[0];
  var right = docW - bounds[2];
  var top = bounds[1];
  var bottom = docH - bounds[3];

  // values to resize to. if left is more than right, 
  // then use the smaller value multiplied by two, 
  // say doc width is 400px, distance from right is 50px, from left is 150px:
  // crop to 400-50*2 = 300px
  var resizeWidth = docW - (left > right ? right * 2: left * 2);
  var resizeHeight = docH - (top > bottom ? bottom  * 2: top * 2);

  doc.resizeCanvas(resizeWidth, resizeHeight)

  // restore original units
  preferences.rulerUnits = startRulerUnits


Whilst the answer above is what you need, (Im not trying to compete with that) it may be useful for future reference to note you can trim to the smallest bounding box and then adjust the canvas size afterwards.

//trim image to transparent width
app.activeDocument.trim(TrimType.TRANSPARENT, true, true, true, true);

// adjust canvas size
//app.activeDocument.resizeCanvas(WIDTH, HEIGHT, AnchorPosition.MIDDLECENTER);
// AnchorPosition can vary, depending on what you want

javascript – Photoshop transparency trimming

Leave a Reply

Your email address will not be published.