[magick-users] Detecting transparency

Anthony Thyssen A.Thyssen at griffith.edu.au
Sun Feb 8 16:02:58 PST 2009


On Sun, 8 Feb 2009 16:02:59 -0500
magick-users-bounces at imagemagick.org wrote:

| On Fri, 6 Feb 2009 23:36:52 -0800
| Dodger <el.dodgero at gmail.com> wrote:
| 
| >Would there be any way to do this in the PerlMagick API, though?
| 
| I don't know if this will help, maybe you can do some
| averaging on the values to get the same results as
| Fred Weinhaus's shell method.
| 
| #!/usr/bin/perl
| use warnings;
| use strict;
| use Image::Magick;
| 
| my $file = shift or die "Need a file $!\n";
| 
| my $img = Image::Magick->new;
| $img->ReadImage($file);
| 
| my $tot = 0;
| my (@colors) = $img->Histogram();
| 
| #print join "\n\n", @colors;
| 
| while (1){
|      if (scalar @colors == 0){last}
|      my $r = shift @colors;
|      my $g = shift @colors;
|      my $b = shift @colors;
|      my $o = shift @colors;
|      my $count = shift @colors; 
|      $tot++;
| 
|         my $rh = sprintf('%02X',$r);
|         my $gh = sprintf('%02X',$g);
|         my $bh = sprintf('%02X',$b);
| 
| print "$count ($rh,$gh,$bh) at $o opacity\n"; 
| }
| 
| print "\n$tot total colors\n";
| 
If all you want is to know if the image has transparency,
do the above and 'short-circuit' the loop as soon as you see
a transparent pixel.

Of course if the input image is JPEG, then it will not have an alpha
channel, so you probably should check as follows.

    if no alpha   NOT TRANSPARENT
    if alpha...
      loop over all pixels
         if any non-opaque, abort loop with 'TRANSPARNT'
      if loop reached end   NOT TRANSPARENT

That will be FAST for JPEG, Generally FAST for images with
transparency, and only slow for images that have alpha
but all pixels are fully-opaque.

That TEST however I believe is in the magick Core somewhere
(Cristy will know) and may be able to be exported for API
usage.

A similar test that is also in MagicCore (somewhere) is
a test for if the image is 'Gray Scale' of not.



  Anthony Thyssen ( System Programmer )    <A.Thyssen at griffith.edu.au>
 -----------------------------------------------------------------------------
   /Earth is 98% full.  Please delete anyone you can!   - rec.humor.funny
 -----------------------------------------------------------------------------
     Anthony's Home is his Castle     http://www.cit.gu.edu.au/~anthony/


More information about the Magick-users mailing list