Search code examples
javascriptpngcroptrimphotoshop-script

Photoshop transparency trimming


i am new in programming and for now i can code only in C#. I really need your help for a Photoshop trimming script. I have searched for days now but cannot find how to achieve what i want. It goes like this. I have a PNG image of a character that is offset from the origin of the canvas. Now I want to trim the transparency equally from both left and right until I hit the first pixel either from left or right (which ever comes first) then stop the trim (which means one side will not be trimmed all the way through because of the offset from origin). Same too for top and bottom. I am desperate for this since weeks and will be very glad if someone can help me. Sample image below.

enter image description here


Solution

  • 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
    

    enter image description here