Skip to content

Instantly share code, notes, and snippets.

@bryanbuchanan
Last active April 1, 2024 09:32
Show Gist options
  • Star 62 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save bryanbuchanan/11387501 to your computer and use it in GitHub Desktop.
Save bryanbuchanan/11387501 to your computer and use it in GitHub Desktop.
Script to find the area of shapes in Adobe Illustrator
/* Save this file with a jsx extension and place in your
Illustrator/Presets/en_US/Scripts folder. You can then
access it from the File > Scripts menu */
var decimalPlaces = 3;
if (app.documents.length > 0) {
if (app.activeDocument.selection.length < 1) {
alert('Select a path');
} else if (app.activeDocument.selection[0].area) {
// Individual Items
var objects = app.activeDocument.selection;
} else if (app.activeDocument.selection[0].pathItems) {
// Group/Compound Shape
var objects = app.activeDocument.selection[0].pathItems;
} else {
alert('Please select a path or group.');
}
// Collect info
var totalArea = 0;
for (var i=0; i<objects.length; i++) {
if (objects[i].area) {
var totalArea = totalArea + objects[i].area;
}
}
// Conversions
var ppi = 72;
var areaIn = totalArea / ppi / ppi;
if (areaIn < 0) var areaIn = -areaIn;
var areaCm = areaIn * 6.4516;
// Display
alert('Shape Area\
' + areaIn.toFixed(decimalPlaces) + ' in² \
' + areaCm.toFixed(decimalPlaces) + ' cm² \n\
' + i + ' shapes');
}
@Dubd
Copy link

Dubd commented Dec 14, 2023

cool script

@hirschferkel
Copy link

hirschferkel commented Dec 14, 2023

@schroef seems you mixed up some things now.

  • the folder has the right permissions
  • $.fileName does not work
  • No prefs are stored with the script.
  • I do not want to store prefs somewhere else
  • I never wanted to store different prefs for different projects

I just saw, that storing the prefs of your script simply does not work. And that’s what I wanted to inform you about and I made some tests for you to check out things.

@hirschferkel
Copy link

@schroef a hard coded path will work

    var f = File("Applications/Adobe Illustrator 2024/Presets.localized/de_DE/Skripten/06_Objektdaten/getShapeArea-savedata.json");
    f.open('w'); // w for 'write'
    f.write(jsonString);
    f.close();
}


function loadJSON(){
    // var jsonString = JSON.stringify(swatchLegenda);
    // Document path
    var pathFile = File($.fileName).path;

    // Scriptpath
    var script = new File($.fileName);
    var textFile = new File(script.path);
    var f = File("Applications/Adobe Illustrator 2024/Presets.localized/de_DE/Skripten/06_Objektdaten/getShapeArea-savedata.json");

@hirschferkel
Copy link

hirschferkel commented Dec 14, 2023

@schroef And in my case there was a wrong line in the script which I downloaded:

    var pathFile = File($.fileName).path;

    // Scriptpath
    var pathFile = new File($.fileName);
    var textFile = new File(script.path);

second var pathFile should be var script I think.

and textfile is /tmp00000001

@hirschferkel
Copy link

At least I found a hack to make it work, when the script is placed in the skripts directory of Illustrator so it will always adapt to the current program folder:
var f = File(app.path + "/Presets.localized/de_DE/Skripten/06_Objektdaten/getShapeArea-savedata.json");

@schroef
Copy link

schroef commented Dec 14, 2023

Ah i see. Still weird that only `$.fileName' does not work. A user on Adobe Community said it does work, see here
He stated perhaps a permission problem on the system?

I also find it kinda strange a hard-coded path only pointing to the folder "Applications" does work. But if it does work, thats your solution.
Well i'm not sure if that correction is correct. Now var pathFile is twice declared.

If the hard-coded path i used you don't need this part. In my version is disabled those. Those where actually test i didn't clean

// Document path
var pathFile = File($.fileName).path;
// Scriptpath
var script = new File($.fileName);
var textFile = new File(script.path);

@hirschferkel
Copy link

hirschferkel commented Dec 14, 2023

@schroef As this is explicitly the only problem which does obviously not work ($.fileName), I will not dig deeper into it. As saving the file does work, now, it is actually no permission problem.

The Application folder is first folder beneath root (Macintosh HD), that's why it works.

You got me wrong again. The file I downloaded had pathFile declared twice and that's wrong. Second var pathFile should have been var Script. That's what I wrote.

@schroef
Copy link

schroef commented Dec 14, 2023

Are you sure you had the past version?
Because the one currently on GitHub doesn't have var pathFile twice?
It has a couple variables, but those are commented out and do nothing
Screenshot_20231214_141009_Chrome

@schroef
Copy link

schroef commented Dec 14, 2023

Are you sure you had the past version?
Because the one currently on GitHub doesn't have var pathFile twice?
It has a couple variables, but those are commented out and do nothing
Screenshot_20231214_141009_Chrome

@hirschferkel
Copy link

Maybe it was during testing so many things it got messed up.

@schroef
Copy link

schroef commented Dec 14, 2023

Ive asked the user on Adobe Community to also test the script, curious if it will work on his side

@hirschferkel
Copy link

@schroef I finally found the issue: I use two different plugins called "Scripts Panel" (same name, but actually from two different developers) to organize my scripts, as Adobe offers such a freaky script menu and each of these break exactly this one code!

Starting the script with Illustrator menu it will make it run!

(I got to it as one guy from the Illustrator Community pointed me to a Sublime script runner, which can execute code from Sublime in Illustrator and there everything worked fine. So I tried to start the script manually from the Illustrator menu instead of starting it from Scripts Panel... and it worked.)

@schroef
Copy link

schroef commented Dec 16, 2023

@hirschferkel

That's great news and superb that you did some more investigation!
I know one of those panels and it very handy.
I guess it suppresses the $fileName in some kind of manner. I always use either file > scripts or use my keymapped hotkey file > scripts> other. That way you can run other scripts quite fast.

Ps is that the script panel from l, I believe he is called Nikita or something in that trend?

@hirschferkel
Copy link

@schroef so thanks so much for your enduring help!
I use a lot of scripts for many different purposes and so I use many different subfolders to organize them somehow properly (Text, Generators, Artboard etc.) The one script offers to close-all-subfolders-but-the-one-in-use option. That's perfect for each project and I did not find a faster way. I assigned some shortcuts, too, but with all these scripts, there is no way to find a proper shortcut sheet ...

@SFR75
Copy link

SFR75 commented Dec 18, 2023

It used to work on my PC. Now I tried your script on OSX + AI 2021. The script produces wrong result. For square with 100pt x 100pt it gives 12.603 cm2. This is quite wrong...

image

@schroef
Copy link

schroef commented Dec 18, 2023

@SFR75
Why is this wrong?
100pt is 3.528cm > 3.528 x 3.528 = 12.445cm2
Which version of the script are you using

@SFR75
Copy link

SFR75 commented Dec 19, 2023

@SFR75 Why is this wrong? 100pt is 3.528cm > 3.528 x 3.528 = 12.445cm2 Which version of the script are you using

I was expecting to see 10.000 or something divisible by 10. Actually I thought it might be related to DPI, so I changed it to 300, but result was the same. Latest version.

@schroef
Copy link

schroef commented Dec 19, 2023

@SFR75
The output is cm and inch not point, you need to select points if you want that. My guess your using the original script. Have a look at my version of this script i've added.

If you use points, you'll get that 10000pt you was expecting
getshapearea-dialog-v016

@schroef
Copy link

schroef commented Dec 20, 2023

@SFR75
You will see 10.000 if you use points as output, but you used inch and centimeter. Using a different metric will show a different value, thats how it works

@whitehorn799
Copy link

Hi, thanks for this script. I really find it useful when trying to calculate the area of my fantasy world's tectonic plates and landmasses. I want to ask if it is just me or are the areas about 10.2% off? I used a rectangle3600x1800 pixels. I divided it up into various irregular polygons within the rectangle. After I went through and measured each "plate", I found that the total areas of the plates equaled 5,880,449.21 pixels squared, but it the area of the rectangle should properly be 6,480,000 pixels squared. Subtracting the sum from the script from the actual total gave me a difference of 599,550.79 pixels squared. Comparing the percentage difference between this and what it should be, I got a percentage difference of exactly 10.2%. I'm not sure if I'm right. I'm just a graphic designer, but I can show you what I did using the image below. What do you think?
discrepancy

@schroef
Copy link

schroef commented Jan 27, 2024

@whitehorn799
Well doing a percentage difference I get about 9.7 percent. Perhaps this is caused by the rounding of the decimals.
Did you manual add all those number or is this done in excel with a function?
I used a calculator on this webpage
https://www.calculator.net/percent-calculator.html?c3par1=6480000&c3par2=5880449.21&ctype=3&x=Calculate#pctdifference

@whitehorn799
Copy link

whitehorn799 commented Jan 28, 2024

I got discrepancies even when the polygon was a regular shape with a whole number as an area, like a square or rectangle. Here's a funny thing I just noticed: if the polygon (regular or irregular) is not snapped to the pixel grid, there's a chance that the script's pixel result will be slightly off because Illustrator gives a fractional pixel value when it isn't aligned to the grid. I would suggest going to Edit>Preferences>General and change Keyboard Increment to 1. Then go to ...>Units and change General and Stroke to Pixels (I think the script doesn't mind whether a polygon has a stroke or not). Then, go to ...>Guides & Grid and change "Gridline every" to 1 px. Go to View>Snap to Grid, and make sure it is checked. Then, in the document, make sure your polygons do not have pixel fractions by looking at the X,Y coordinates and the Width, Height dimensions in the Transform panel.

This fixes regular polygon area calculations, but if your polygon is crazy, like some of mine, I think the script may still throw fractions of pixels, and I think that's understandable.

Another suggestion: there's a chance that totalArea will return negative, so you may want to include a line to fix that up. Again, please let me know if I am way off base, just a graphic designer here!

I still get a discrepancy after re-calculating all the plates with this new method, only this time the results are less consistent, with a 12.17% difference for pixels, 14.25% difference in miles, and a 10.17% difference in kilometers. I think it's just the nature of the beast of rounding numbers, eh?

I'm working with numbers in the millions, so would there be a way to convert the results into numbers with proper commas?

@schroef
Copy link

schroef commented Jan 31, 2024

@whitehorn799
Well I'm not sure how the area is calculated. It's an internal function, so perhaps something weird is going on there. Though I've never,not to my knowledge seen faulty outcome.
If I would place a 4x3 cm or pixel format randomly on the canvas, the outcome is the same
Are you willing to share your document?

@whitehorn799
Copy link

https://www.dropbox.com/scl/fi/satcipmjk8u7vcenqfbc3/Tectonics.eps?rlkey=gu2t4arwv664vk78v0ev8i48c&dl=0 You can take a look if you like. I put two white squares on there and turned off the snap to pixel grid. The area of the smaller square is about 2 hundredths off, and the square has fractional pixel dimensions. If you turn on the grid, and you give the square whole numbers as WxH dimensions, the result is correct. Like I said, though, it's quite easy and close enough, I think!

@schroef
Copy link

schroef commented Feb 8, 2024

@whitehorn799

thanks for highlighting this. It seems there is indeed and issue somewhere. I check the raw output of the area. Thats the negative number in the screengrab. Right is the number from that big white square. Which does have its awkward not rounded number 717 x x716.9996 px
convert issue points

I need to go over the code and see whats cause this.
Whats weird is that i checked it with lower values and it always seemed to return proper area values. like says 10x10 or 100x100
I think its an issue with using pixels and the conversion. If i use mm as ruler input and use those values of the square. I get 252.942 mm x 252.942 mm = 63979.655364 from a calculator and 63979.57105 from the script. Still not correct, but its closer

I think its due to my hot mess of using different decimals. i should look into this and make this neater code.
conversion-code-hot-mess

@whitehorn799
Copy link

Yeah, there seems to be a narrow margin of error that gets exponentially more noticeable. Glad to help where I can!

@schroef
Copy link

schroef commented Feb 15, 2024

@whitehorn799
Im still working on some other issues inbumpedninto. I noticed when a selection consists of multiple compoundpathitems, it would return the shape count as 1. Currently working on that. I believe the calculations are now fixed. As far as I can do that. I've noticed that still sometimes it returns a none round number even when the length and with are round numbers.. the pixel area is now as close as I can get it

@whitehorn799
Copy link

Cool, thanks for updating this and helping out! I appreciate all the work you've done. Will you update the code when you iron out those bumps you were talking about?

@schroef
Copy link

schroef commented Feb 15, 2024

@whitehorn799

Of course I will

@draugmot
Copy link

draugmot commented Mar 23, 2024

For some reasons, it got negative area for some paths, so for multiple paths it substracted them. not added. Fixed with adding math.abs:
var totalArea = totalArea + Math.abs(objects[i].area);

But unfortunately, now compound shape calculation doesn't work correctly ¯_(ツ)_/¯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment