Pre-crop PNG image to alpha and get offset

I have a set of images, all with the same size, saved in PNG format.

Later, in my program, I will use these images and lay them on top of each other.

However, the opaque part of each of these images is actually very small. Therefore, to improve performance, it would be better to use images cropped to alpha, so that each image is cropped to the smallest possible rectangle containing all non-alpha pixels.

When drawing each image on top of the other, I will only need to draw this cropped image with an offset.

There are many images, so it should not be done manually - and this is not what I would like to do when I first start my program.

In other words, I'm looking to create a batch job that can handle this efficiently.

ImageMagick has a β€œcrop” that does what I'm looking for, except that I need to lock the offset. This offset should somehow accompany the image - either by writing the offsets to the file, or by entering it in the file name (for example, overlay123.png can become overlay123-34x99.png if the offset is 34x99).

What is the best tool for the job? I could write such a procedure to do it manually, but it seems that there should be several command line utilities that I could use, or do it in several lines in some scripting language.

+4
source share
1 answer

Starting with a simple trim command:

convert test.png -trim +repage test2.png 

you can add the -identify :

 convert test.png -trim -identify +repage test2.png 

the output of this command will be:

 test.png PNG 800x600=>566x483 800x600+161+52 8-bit DirectClass 0.000u 0:00.004 

where 800x600 is the size of the original image, 566x483 is the size of the resulting image, and + 161 + 52 is the offset of the rectangle containing the non-alpha part of the image. Using the latest information, you can build a little script to achieve your goal.

+4
source

Source: https://habr.com/ru/post/1481463/


All Articles