Testing for image transparency

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like "How do I use ImageMagick to create drop shadows?".
Post Reply
squiddy
Posts: 16
Joined: 2018-09-27T02:53:52-07:00
Authentication code: 1152

Testing for image transparency

Post by squiddy » 2019-05-24T01:57:46-07:00

I'm using a Python library that creates pngs, but once in a blue moon, generates a set of pngs that are essentially just transparent. I have no idea why and it's a rare enough event not to want to bother investigating.

The images are intended for social media, and I'd like to be able to test for transparency before they get sent & if there's a problem, we can rerun the image generator & alert the admin (me).

I found this snippet of code on a (very) old post, and it works perfectly (on Linux 32bit IM 6.9.10), but I wondered if there is a neater/quicker/whatever equivalent for both 6.9 and 7.x ?

Code: Select all

convert image -matte -channel A -separate -format '%[fx:image.maxima]' info: 

User avatar
fmw42
Posts: 25260
Joined: 2007-07-02T17:14:51-07:00
Authentication code: 1152
Location: Sunnyvale, California, USA

Re: Testing for image transparency

Post by fmw42 » 2019-05-24T08:29:11-07:00

Not really that I know. But your syntax is out of date. It should be

convert image -alpha on -channel A -format "%[fx:maxima]\n" info:

opaque:

Code: Select all

convert logo: -alpha on -channel a -separate -format "%[fx:maxima]\n" info:
1
partially transparent:

Code: Select all

convert logo: -transparent white logot.png
convert logot.png -alpha on -channel a -separate -format "%[fx:maxima]\n" info:
1
fully transparent:

Code: Select all

convert logo: -alpha on -channel a -evaluate set 0 +channel logot2.png
convert logot2.png -alpha on -channel a -separate -format "%[fx:maxima]\n" info:
0
If you want to detect partial transparency, change maxima to mean.

If you only want to check if fully opaque, then you can use

Code: Select all

convert image -format "%[opaque]\" info:

Code: Select all

convert logo: -format "%[opaque]\n" info:
true

Code: Select all

convert logot.png -format "%[opaque]\n" info:
false

Code: Select all

convert logot2.png -format "%[opaque]\n" info:
false

See https://imagemagick.org/script/escape.php

squiddy
Posts: 16
Joined: 2018-09-27T02:53:52-07:00
Authentication code: 1152

Re: Testing for image transparency

Post by squiddy » 2019-05-24T11:37:37-07:00

Thanks very much indeed.
Yes, definitely would have been out of date as I harvested that from a 2008 post on this board.

Post Reply