PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to check if a GIF has transparency using GD?

 October 10, 2022     gd, image-processing, php, php-gd     No comments   

Issue

I saw this thread and the solutions perfectly works but for PNG only. Is there a solution for checking if a GIF image has transparency in PHP-GD?


Solution

I am less familiar with GIFs than other formats, so my assumptions may be incorrect. Please let me know if I am wrong - a simple comment, rather than a down-vote, would be appreciated.

I am assuming that:

  • all GIFs are palettised,
  • the alpha component will be non-zero (probably 127) for any palette entry which is transparent,
  • encoders do not add transparent palette entries unnecessarily.

On that basis, the following code will load a GIF and check that no palette entry contains transparency - rather than checking every single pixel in a very slow double loop over height and width of an image:

<?php

function GIFcontainstransparency($fname){

   // Load up the image
   $src=imagecreatefromgif($fname);

   // Check image is palettised
   if(imageistruecolor($src)){
      fwrite(STDERR,"ERROR: Unexpectedly got a truecolour (non-palettised) GIF!");
   }

   // Get number of colours - i.e. number of entries in palette
   $ncolours=imagecolorstotal($src);

   // Check palette for any transparent colours rather than all pixels - to speed it up
   for($index=0;$index<$ncolours;$index++){
      $rgba = imagecolorsforindex($src,$index);
      if($rgba['alpha']>0){
         return true;
      }
   }
   return false;
}

////////////////////////////////////////////////////////////////////////////////
// main
////////////////////////////////////////////////////////////////////////////////

   if(GIFcontainstransparency("image.gif")){
      echo "Contains transparency";
   } else {
      echo "Is fully opaque";
   }
?>


Answered By - Mark Setchell
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing