Shedrack Okolie
Shedrack Okolie

Reputation: 25

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

Upvotes: 2

Views: 1097

Answers (2)

Ghoul Fool
Ghoul Fool

Reputation: 6967

Whilst the answer above is what you need, (I'm 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

Upvotes: 3

Sergey Kritskiy
Sergey Kritskiy

Reputation: 2269

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

Upvotes: 2

Related Questions