编程语言
首页 > 编程语言> > php – 什么可能导致imagecolorsforindex()的“颜色索引超出范围”错误?

php – 什么可能导致imagecolorsforindex()的“颜色索引超出范围”错误?

作者:互联网

当修补程序调整大量的JPG,PNG和GIF文件时,PHP会出现意外丢失,并显示以下错误消息:

imagecolorsforindex() [function.imagecolorsforindex]:
Color index 226 out of range

相关的代码片段是:

protected function preserveTransparency($img, $resized, $ftype) {

    if (($ftype == IMAGETYPE_PNG) || ($ftype == IMAGETYPE_GIF)) {
        $tidx = imagecolortransparent($img);
        if ($tidx >= 0) {
          $transColor = imagecolorsforindex($img, $tidx);
          $tidx = imagecolorallocate($resized, $transColor['red'], $transColor['green'], $transColor['blue']);
          imagefill($resized, 0, 0, $tidx);
          imagecolortransparent($resized, $tidx);
        } elseif ($ftype == IMAGETYPE_PNG) {
            imagealphablending($resized, false);
            imagesavealpha($resized, true);
            $transparent = imagecolorallocatealpha($resized, 255, 255, 255, 127);
            imagefill($resized, 0, 0, $transparent);
        }
    }
}

如果已经由imagecolortransparent返回,颜色索引怎么可能不存在?

解决方法:

听起来像imagecolortransparent($img)返回的索引大于相关图像的托盘大小.

透明度颜色的索引是图像的属性,而不是托盘的属性,因此有可能在托盘大小之外使用此索引集创建图像,但我希望PHP会检测到这个并在这种情况下从imagecolortransparent()返回-1.

您可以通过向代码添加对imagecolorstotal的调用来检查是否发生了这种情况:

    $tidx = imagecolortransparent($img);
    $palletsize = imagecolorstotal($img);
    if ($tidx >= 0 && $tidx < $palletsize) {
      $transColor = imagecolorsforindex($img, $tidx);

标签:php,image-processing,imagemagick,image-manipulation,gd
来源: https://codeday.me/bug/20190610/1212557.html