如何使用GD检查图像是否具有透明度?

问题描述 投票:12回答:8

如何使用php的GD库检查图像是否具有透明像素?

php image-processing gd
8个回答
5
投票

看起来您不能一目了然地检测透明度。

The comments on the imagecolorat manual page建议使用真彩色图像时得到的整数实际上可以总共移动四次,第四个是alpha通道(其他三个是红色,绿色和蓝色)。因此,给定$x$y的任何像素位置,您可以使用以下方法检测alpha:

$rgba = imagecolorat($im,$x,$y);
$alpha = ($rgba & 0x7F000000) >> 24;
$red = ($rgba & 0xFF0000) >> 16;
$green = ($rgba & 0x00FF00) >> 8;
$blue = ($rgba & 0x0000FF);

127的$alpha显然是完全透明的,而零是完全不透明的。

不幸的是,您可能需要处理图像中的每个像素,只是为了找到一个透明的像素,然后这只适用于真彩色图像。否则imagecolorat返回一个颜色索引,然后你必须使用imagecolorsforindex查找,它实际上返回一个带有alpha值的数组。


14
投票

我知道这是旧的,但我刚刚在PHP文档的评论中找到了这个。 (link

以下是确定PNG图像是否包含alpha的函数:

<?php
    function is_alpha_png($fn){
      return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6);
    }
?>

PNG图像的颜色类型存储在字节偏移25处。该第25个字节的可能值为:

  • 0 - 灰度
  • 2 - RGB
  • 3 - 带调色板的RGB
  • 4 - 灰度+ alpha
  • 6 - RGB + alpha

仅适用于PNG图像。


5
投票

可以办到!

我将所有答案和评论合并到一个应该快速可靠的功能中:

function hasAlpha($imgdata) {
    $w = imagesx($imgdata);
    $h = imagesy($imgdata);

    if($w>50 || $h>50){ //resize the image to save processing if larger than 50px:
        $thumb = imagecreatetruecolor(10, 10);
        imagealphablending($thumb, FALSE);
        imagecopyresized( $thumb, $imgdata, 0, 0, 0, 0, 10, 10, $w, $h );
        $imgdata = $thumb;
        $w = imagesx($imgdata);
        $h = imagesy($imgdata);
    }
    //run through pixels until transparent pixel is found:
    for($i = 0; $i<$w; $i++) {
        for($j = 0; $j < $h; $j++) {
            $rgba = imagecolorat($imgdata, $i, $j);
            if(($rgba & 0x7F000000) >> 24) return true;
        }
    }
    return false;
}

//SAMPLE USE:
hasAlpha( imagecreatefrompng("myfile.png") );   //returns true if img has transparency

4
投票

我知道这是一个老线程,但在我看来,它需要改进,因为通过检查所有像素只是为了发现它不透明是一个浪费的时间。所以经过一些谷歌搜索后我找到了Jon Fox's Blog,并且我在W3C PNG Specification的帮助下进一步提高了他的代码的可靠性,快速性和内存印记的最小值:

function IsTransparentPng($File){
    //32-bit pngs
    //4 checks for greyscale + alpha and RGB + alpha
    if ((ord(file_get_contents($File, false, null, 25, 1)) & 4)>0){
        return true;
    }
    //8 bit pngs
    $fd=fopen($File, 'r');
    $continue=true;
    $plte=false;
    $trns=false;
    $idat=false;
    while($continue===true){
        $continue=false;
        $line=fread($fd, 1024);
        if ($plte===false){
            $plte=(stripos($line, 'PLTE')!==false);
        }
        if ($trns===false){
            $trns=(stripos($line, 'tRNS')!==false);
        }
        if ($idat===false){
            $idat=(stripos($line, 'IDAT')!==false);
        }
        if ($idat===false and !($plte===true and $trns===true)){
            $continue=true;
        }
    }
    fclose($fd);
    return ($plte===true and $trns===true);
}

2
投票

相当直接的功能,它将检查图像中是否有任何透明像素,如果是,它将返回true。

$im = imagecreatefrompng('./transparent.png');
if(check_transparent($im)) {
    echo 'DA';
}
else {
    echo 'NU';
}

function check_transparent($im) {

    $width = imagesx($im); // Get the width of the image
    $height = imagesy($im); // Get the height of the image

    // We run the image pixel by pixel and as soon as we find a transparent pixel we stop and return true.
    for($i = 0; $i < $width; $i++) {
        for($j = 0; $j < $height; $j++) {
            $rgba = imagecolorat($im, $i, $j);
            if(($rgba & 0x7F000000) >> 24) {
                return true;
            }
        }
    }

    // If we dont find any pixel the function will return false.
    return false;
}

1
投票

这就是我检测8-32位透明度的方法。它只适用于PNG。

function detect_transparency($file){

    if(!@getimagesize($file)) return false;

    if(ord(file_get_contents($file, false, null, 25, 1)) & 4) return true;

    $content = file_get_contents($file);
    if(stripos($content,'PLTE') !== false && stripos($content, 'tRNS') !== false) return true;

    return false;
}

0
投票

cronoklee的功能非常好,但是当我使用它时,我发现了一个bug。它不适用于8位托盘的图像。这是固定的变体:

public function hasAlpha($imgdata)
{
    $w = imagesx($imgdata);
    $h = imagesy($imgdata);

    if($w>100 || $h>100){ //resize the image to save processing
        $thumb = imagecreatetruecolor(100, 100);
        imagealphablending($thumb, FALSE);
        imagecopyresized( $thumb, $imgdata, 0, 0, 0, 0, 100, 100, $w, $h );
        $imgdata = $thumb;
        $w = imagesx($imgdata);
        $h = imagesy($imgdata);
    }
    //run through pixels until transparent pixel is found:
    for($i = 0; $i<$w; $i++) {
        for($j = 0; $j < $h; $j++) {
            $ci = imagecolorat($imgdata, $i, $j);
            $rgba = imagecolorsforindex($imgdata, $ci);
            if($rgba['alpha']) { return true; }
        }
    }
    return false;
}

0
投票

改进了cronoklee的功能。删除了每个像素的不必要的位移,减少了假阴性计数,在功能描述中添加了解释。

/**
 * Estimates, if image has pixels with transparency. It shrinks image to 64 times smaller
 * size, if necessary, and searches for the first pixel with non-zero alpha byte.
 * If image has 1% opacity, it will be detected. If any block of 8x8 pixels has at least
 * one semi-opaque pixel, the block will trigger positive result. There are still cases,
 * where image with hardly noticeable transparency will be reported as non-transparent,
 * but it's almost always safe to fill such image with monotonic background.
 *
 * Icons with size <= 64x64 (or having square <= 4096 pixels) are fully scanned with
 * absolutely reliable result.
 *
 * @param  resource $image
 * @return bool
 */
function hasTransparency ($image): bool {
  if (!is_resource($image)) {
    throw new \InvalidArgumentException("Image resource expected. Got: " . gettype($image));
  }

  $shrinkFactor      = 64.0;
  $minSquareToShrink = 64.0 * 64.0;

  $width  = imagesx($image);
  $height = imagesy($image);
  $square = $width * $height;

  if ($square <= $minSquareToShrink) {
    [$thumb, $thumbWidth, $thumbHeight] = [$image, $width, $height];
  } else {
    $thumbSquare = $square / $shrinkFactor;
    $thumbWidth  = (int) round($width / sqrt($shrinkFactor));
    $thumbWidth < 1 and $thumbWidth = 1;
    $thumbHeight = (int) round($thumbSquare / $thumbWidth);
    $thumb       = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagealphablending($thumb, false);
    imagecopyresized($thumb, $image, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
  }

  for ($i = 0; $i < $thumbWidth; $i++) { 
    for ($j = 0; $j < $thumbHeight; $j++) {
      if (imagecolorat($thumb, $i, $j) & 0x7F000000) {
        return true;
      }
    }
  }

  return false;
}

Usage:

hasTransparency( imagecreatefrompng("myfile.png") );   //returns true if img has transparency
© www.soinside.com 2019 - 2024. All rights reserved.