Skip to main content
October 2, 2015
Question

How Do I Write A Script Resizing A Layer To Canvas & Keeping The Aspect Ratio

  • October 2, 2015
  • 2 replies
  • 2112 views

Hello Everybody

I'm looking for a script that would resize a layer to fit a canvas of 34cm wide by 40cm high, but that would also take into account the aspect ratio of the layer so it doesn't warp the image.

I'm really sorry I'm absolutely useless at script writing and admit I have no skill in this area, any help would be amazing. Thank you

This topic has been closed for replies.

2 replies

Chuck Uebele
Community Expert
Community Expert
October 2, 2015

As JJ Mack stated it's just math: figuring out your file size in pixels and you layer size in pixels, then sizing the layer.

#target photoshop 

var oldPref = app.preferences.rulerUnits 

app.preferences.rulerUnits = Units.PIXELS; 

var doc = activeDocument;

var iLayer = doc.activeLayer; 

doc.activeLayer = iLayer; 

var scale = Math.max(doc.width/(iLayer.bounds[2]-iLayer.bounds[0]),doc.height/(iLayer.bounds[3]-iLayer.bounds[1])); 

iLayer.resize (scale*100,scale*100); 

iLayer.translate(doc.width/2-(iLayer.bounds[0]+iLayer.bounds[2])/2,doc.height/2-(iLayer.bounds[1]+iLayer.bounds[3])/2); 

Moving to Photoshop Scripting forum

JJMack
Community Expert
Community Expert
October 2, 2015

There is a scripting forum and if you search it you will find code there that will answer your question. You can also read Adobe Fit Image Plug-in script to see how whole documents can be resized and maintain aspect ratio. Its simple math.

https://forums.adobe.com/search.jspa?place=%2Fplaces%2F1383833&sort=updatedDesc&q=resize+layer+aspect+ratio



Photoshop Scripting




You can also fit an imag into and area without distorting it by  resizing it to fill the area then masking off any excess . A virtual center crop to the new aspect ratio.  For example the script will resize the current layer to fit within four guides you first set.

http://www.mouseprints.net/old/dpr/FitImageToGuides.jsx

JJMack
October 2, 2015

Thanks, I'll give that a go.

JJMack
Community Expert
Community Expert
October 2, 2015

With that script if you set guides to the canvas four any current layer above the background canvas would be resized to fill the canvas and excess would be outside the canvas area. Layers other then the background layer can be any size.  It would be best if any layer you want to resize is converted to a smart object layer first before you uset that script.

JJMack