PHP imagick or any other tool, how to detect if there is visible transparency on gifs files

戏子无情 提交于 2020-05-13 14:37:05

问题


I am working on a service that can do conversions from gif to mp4 files (with ffmpeg).

My problem is some of the gifs have visible transparent areas which end up as white color when I convert them to mp4 video. To avoid that problem I am trying detect if a gif has visible transparent areas so I will avoid converting them to mp4.

I tried to use getImageAlphaChannel() function from imagick.

   if ($imagick->getImageAlphaChannel()) {
      echo 'transparent image';
   } else {
      echo 'not transparent image';   
   }

This function works correctly reports transparent for images like below; which has obvious visible transparent areas.

transparent gif 1

But it also reports transparent for images like below;

false transparent gif 1

false transparent gif 2

This result is probably correct for imagick , probably above images are transparent , but according to my eyes there are no visible transparent areas.

My question is how can I correctly identify, if a gif file that has visible transparent areas or it is even possible with imagick or any other tool ?


回答1:


You can use the Imagick::getImageChannelRange to evaluate the min/max of values used by a specific color channel.

$alphaRange = $imagick->getImageChannelRange(Imagick::CHANNEL_ALPHA);

You can then check if there is any transparency with...

$hasTransparency = $alphaRange['minima'] < $alphaRange['maxima'];
  • If the channel is defined, and has any transparent areas across any frame, then maxima will always be greater then minima.

  • If the channel is NOT defined, then minima will be Inf placeholder, and maxima will be -Inf placeholder, so the above check will still work.

  • If the whole image has a consistent alpha-value (i.e. full transparency, or no data variation), this solution would not work. A fallback check could be something like... minima == maxima AND minima > 0

Another great benefit from evaluating ranges is that you can check the distance between the two min/max values against a threshold, so a "little semi-transparency" can be identified & isolated.

$threshold = $imagick->getQuantum() * 0.1; // < 10% is okay.
$hasTransparency = $alphaRange['minima'] < $alphaRange['maxima']
                 && ($alphaRange['maxima'] - $alphaRange['minima']) < $threshold;


来源:https://stackoverflow.com/questions/52284397/php-imagick-or-any-other-tool-how-to-detect-if-there-is-visible-transparency-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!