• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Find crop aspect ratio from selection or image? [SOLVED]

Engaged ,
Jun 02, 2022 Jun 02, 2022

Copy link to clipboard

Copied

Is there a way (maybe a workaround?) to find the aspect ratio of a selection or an image?

Let's say I have a document and inside that document I have a photo. I would like to select that photo and using that selection, being able to automatically know what the aspect ratio is so I can then create a crop preset based on that.

 

Sure, I could use the size of the image as my W and H, but I was thinking if it was possible to have it done (kinda) automatically and also, instead of having an aspect ratio of 1489 by 933, I would have something a bit simpler (lower numbers the same way we have 16:9, 4:5, etc).

TOPICS
macOS

Views

1.2K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Jun 03, 2022 Jun 03, 2022

@TiagoRocha – Further to my previous reply, I have created an "offshoot" of the previously mentioned script to report on the active selection ratio:

script.png

 

/*
Photoshop Selection Info - Aspect Ratio.jsx
Stephen Marsh - v1.0, 3rd June 2022
*/

#target photoshop

var savedRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var selectionBounds = activeDocument.selection.bounds;
/*
var selectionLeft = selectionBounds[0].value;
var selectionTop = selectionBounds[1].value;
var s
...

Votes

Translate

Translate
Adobe
Community Expert ,
Jun 02, 2022 Jun 02, 2022

Copy link to clipboard

Copied

There isn't such built in function. The only way I can think of is using script. I am not scripter nor sure it can be done. Wait for @c.pfaffenbichler @Stephen_A_Marsh @Kukurykus @r-bin 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

Yes, that's what I thought. A script would probably be the best option. It would be great if Photoshop had that implemented with a right click over a selection.

Anyway, Stephen came to the rescue and shared some valuable scripts 🙂

Thanks for tagging those people on your reply!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jun 02, 2022 Jun 02, 2022

Copy link to clipboard

Copied

The following script that I created is for a document, not a selection, however it is simple enough to modify. Three different aspect ratio formulas are used, they don't always agree!

 

https://github.com/MarshySwamp/Photoshop-Document-Dimensions---MP-Value---Aspect-Ratio/blob/main/Pho...

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

@TiagoRocha – Further to my previous reply, I have created an "offshoot" of the previously mentioned script to report on the active selection ratio:

script.png

 

/*
Photoshop Selection Info - Aspect Ratio.jsx
Stephen Marsh - v1.0, 3rd June 2022
*/

#target photoshop

var savedRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var selectionBounds = activeDocument.selection.bounds;
/*
var selectionLeft = selectionBounds[0].value;
var selectionTop = selectionBounds[1].value;
var selectionRight = selectionBounds[2].value;
var selectionBottom = selectionBounds[3].value;
var selectionXCenter = (selectionBounds[0].value + selectionWidth) / 2;
var selectionYCenter = (selectionBounds[1].value + selectionHeight) / 2;
*/
var selectionWidth = selectionBounds[2].value - selectionBounds[0].value;
var selectionHeight = selectionBounds[3].value - selectionBounds[1].value;
var r = gcd(selectionWidth, selectionHeight);
var ratio = selectionWidth / selectionHeight;
alert(
    'Selection Info' + '\n' +
    'Selection Width: ' + selectionWidth + ' px' + '\n' +
    'Selection Height: ' + selectionHeight + ' px' + '\n' +
    'Aspect Ratio:' + '\n' + ratio.toFixed(2) + ':1' + ' / ' + ratio.toFixed(2) * 2 + ':2 / ' + ratio.toFixed(2) * 4 + ':4' + ' (Basic)' + '\n' +
    selectionWidth / r + ':' + selectionHeight / r + ' (GCD)' + '\n' +
    aspect_ratio(selectionWidth / selectionHeight, 50).toString().replace(',', ':') + ' (Farey)'
);
app.preferences.rulerUnits = savedRuler;


function gcd(a, b) {
    /* https://stackoverflow.com/questions/1186414/whats-the-algorithm-to-calculate-aspect-ratio-i-need-an-output-like-43-169 */
    return (b == 0) ? a : gcd(b, a % b);
}

function aspect_ratio(val, lim) {
    var lower = [0, 1];
    var upper = [1, 0];
    while (true) {
        var mediant = [lower[0] + upper[0], lower[1] + upper[1]];

        if (val * mediant[1] > mediant[0]) {
            if (lim < mediant[1]) {
                return upper;
            }
            lower = mediant;
        } else if (val * mediant[1] == mediant[0]) {
            if (lim >= mediant[1]) {
                return mediant;
            }
            if (lower[1] < upper[1]) {
                return lower;
            }
            return upper;
        } else {
            if (lim < mediant[1]) {
                return lower;
            }
            upper = mediant;
        }
    }
}

 

  1. Copy the code text to the clipboard
  2. Open a new blank file in a plain-text editor (not in a word processor)
  3. Paste the code in
  4. Save the text file as .txt
  5. Rename the file extension from .txt to .jsx
  6. Install or browse to the .jsx file to run:

https://prepression.blogspot.com/2017/11/downloading-and-installing-adobe-scripts.html#Photoshop

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

Amazing @Stephen_A_Marsh ! Thank you so much for those scripts. I just saved both of them 🙂

 

I have a few questions:

1 - Since this section below is just a comment, I can go ahead and just delete it, right?

 

/*
var selectionLeft = selectionBounds[0].value;
var selectionTop = selectionBounds[1].value;
var selectionRight = selectionBounds[2].value;
var selectionBottom = selectionBounds[3].value;
var selectionXCenter = (selectionBounds[0].value + selectionWidth) / 2;
var selectionYCenter = (selectionBounds[1].value + selectionHeight) / 2;
*/

 

 

2 - From what I saw, the scripts are only showing the information about the ratios available, correct? It's not supposed to perform any action once we hit the OK button, right?

 

3 - An improvement to the scripts (if that's not much work and you see it as an improvement, of course) would be to have 3 buttons instead of just the OK button. So:

- The OK button would become a Close button instead

- One button could be something like Apply Crop. This would activate the Crop Tool and automatically add that ratio to the W and H fields so the user could automatically see what the numbers are and apply the crop right away

- One button like New Crop Preset. This would activate the Crop Tool, add the numbers to the W and H fields, then would automatically select the New Crop Preset... option from the menu. Then the user would be able to just type a custom name and hit Ok.

 

Anyway, these scripts alone are already a great help, so I truly appreciate you sharing them and spending the time adapting the original one to my request 🙂

If you believe adding those extra functions would be a good improvement, let me know.

 

Thanks again for your precious contribution!!!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

@TiagoRocha 

 

(1) Yes, I commented out the unused code portions to leave them as a placeholder, just in case you came back and said that you wanted to know the selection X/Y values or the centre etc.

 

(2) That is correct, I didn't know 100% what you wanted to do, except that you mentioned that you wanted to know the aspect ratio of an image or selection.

 

(3) Anything to do with adding a custom interface with buttons in JavaScript is a huge undertaking (for me). Lots of code, lots of bug testing and extra development time.

 

Simply automatically cropping after the info is presented, or confirming to crop the selection or not is easy, the confirmation interface does not require a great deal of work as it uses an operating system interface call. Same for a second confirmation asking whether to save a crop preset... However, I don't recall if I have previously scripted a crop preset so I don't know if this is possible or the complexity.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

@TiagoRocha – This version offers a confirmation dialog to ask whether to crop or not. There is an option to delete or retain cropped pixels commented in the code:

 

/*
Photoshop Selection Info - Aspect Ratio and Crop.jsx
Stephen Marsh - v1.0, 4th June 2022
*/

#target photoshop

var savedRuler = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var selectionBounds = activeDocument.selection.bounds;
var selectionWidth = selectionBounds[2].value - selectionBounds[0].value;
var selectionHeight = selectionBounds[3].value - selectionBounds[1].value;
var r = gcd(selectionWidth, selectionHeight);
var ratio = selectionWidth / selectionHeight;
alert(
    'Selection Info' + '\n' +
    'Selection Width: ' + selectionWidth + ' px' + '\n' +
    'Selection Height: ' + selectionHeight + ' px' + '\n' +
    'Aspect Ratio:' + '\n' + ratio.toFixed(2) + ':1' + ' / ' + ratio.toFixed(2) * 2 + ':2 / ' + ratio.toFixed(2) * 4 + ':4' + ' (Basic)' + '\n' +
    selectionWidth / r + ':' + selectionHeight / r + ' (GCD)' + '\n' +
    aspect_ratio(selectionWidth / selectionHeight, 50).toString().replace(',', ':') + ' (Farey)'
);

if (confirm("Crop to selection: Yes or No?", false)) {
    // Crop to selection
    try {
        cropToSelection(selectionBounds[1], selectionBounds[0], selectionBounds[3], selectionBounds[2], true); // delete cropped pixels
    } catch (e) {
        alert('There was an unexpected error when cropping');
    }
    // throw alert("Script cancelled!");
    throw null;
}

app.preferences.rulerUnits = savedRuler;


function gcd(a, b) {
    /* https://stackoverflow.com/questions/1186414/whats-the-algorithm-to-calculate-aspect-ratio-i-need-an-output-like-43-169 */
    return (b === 0) ? a : gcd(b, a % b);
}

function aspect_ratio(val, lim) {
    var lower = [0, 1];
    var upper = [1, 0];
    while (true) {
        var mediant = [lower[0] + upper[0], lower[1] + upper[1]];

        if (val * mediant[1] > mediant[0]) {
            if (lim < mediant[1]) {
                return upper;
            }
            lower = mediant;
        } else if (val * mediant[1] == mediant[0]) {
            if (lim >= mediant[1]) {
                return mediant;
            }
            if (lower[1] < upper[1]) {
                return lower;
            }
            return upper;
        } else {
            if (lim < mediant[1]) {
                return lower;
            }
            upper = mediant;
        }
    }
}

function cropToSelection(top, left, bottom, right, retainPixels) {
    // Courtesy of Chuck Uebele
    var origRuler = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;
    // Crop to selection with retain cropped pixels option
    var idCrop = charIDToTypeID("Crop");
    var desc11 = new ActionDescriptor();
    var idT = charIDToTypeID("T   ");
    var desc12 = new ActionDescriptor();
    var idTop = charIDToTypeID("Top ");
    var idPxl = charIDToTypeID("#Pxl");
    desc12.putUnitDouble(idTop, idPxl, top);
    var idLeft = charIDToTypeID("Left");
    desc12.putUnitDouble(idLeft, idPxl, left);
    var idBtom = charIDToTypeID("Btom");
    desc12.putUnitDouble(idBtom, idPxl, bottom);
    var idRght = charIDToTypeID("Rght");
    desc12.putUnitDouble(idRght, idPxl, right);
    var idRctn = charIDToTypeID("Rctn");
    desc11.putObject(idT, idRctn, desc12);
    var idAngl = charIDToTypeID("Angl");
    var idAng = charIDToTypeID("#Ang");
    desc11.putUnitDouble(idAngl, idAng, 0.000000);
    var idDlt = charIDToTypeID("Dlt ");
    // Delete cropped pixels = true | false
    desc11.putBoolean(idDlt, retainPixels);
    var idcropAspectRatioModeKey = stringIDToTypeID("cropAspectRatioModeKey");
    var idcropAspectRatioModeClass = stringIDToTypeID("cropAspectRatioModeClass");
    var idtargetSize = stringIDToTypeID("targetSize");
    desc11.putEnumerated(idcropAspectRatioModeKey, idcropAspectRatioModeClass, idtargetSize);
    executeAction(idCrop, desc11, DialogModes.NO);
    // Reset rulers to previous value
    app.preferences.rulerUnits = origRuler;
}

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Jun 04, 2022 Jun 04, 2022

Copy link to clipboard

Copied

LATEST

Thank you again for your time and help!

This last code isn't as valuable to me as the other ones, because when I'm using this feature, it's more of a way for me to know the ratio of a particular section, not to really crop it. If I had the ability to press a button and make it automatically create the preset, that would be an improvement, but cropping it right away is not the intention...

I know that on my request I wrongfully mentioned the Apply Crop button, but now looking back, it doesn't make sense that I mentioned that (at least not for my original intention for this feature). Maybe other users will find it useful though, knowing the ratio before cropping something? 🙂

 

Anyway, when I tried it, I got an error, after it was able to crop it successfully:

Screen Shot 2022-06-04 at 10.40.40 AM.png

 

Again, thanks for your help. I totally understand that something as complex as this would require a lot of extra work and to me, the first 2 scripts are already a HUGE help, because I was struggling with this on a regular basis and this will save me a lot of time, so THANKS!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Jun 02, 2022 Jun 02, 2022

Copy link to clipboard

Copied

Could you elaborate and give examples/screenshots? 

Why do you need to create a Preset, wouldn’t Image > Crop work just as well when you have a Selection anyway? 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Jun 03, 2022 Jun 03, 2022

Copy link to clipboard

Copied

For example, let's say I just created my official website using WordPress and installed a particular theme. Each theme has different sizes when it comes to post thumbnails/featured images. So if I'm creating new posts on a regular basis and I use stock images, for example, I want to be able to create a crop preset so I can always crop those images to fit the ratio of my Wordpress theme.

 

So I would just take a screenshot of my website's front page with all the post thumbnails, and then paste it into Photoshop, create a selection around one of the thumbnails and create the crop preset.

 

Hope it makes sense...

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines