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

2024-02-25

当对一大堆 JPG、PNG 和 GIF 文件进行补丁大小调整时,PHP 意外地死机,并显示以下错误消息:

imagecolorsforindex() [function.imagecolorsforindex]: 颜色索引 226 超出范围

相关代码片段是:

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 能够检测到这一点并从返回-1imagecolortransparent()在这个情况下。

您可以通过添加调用来检查是否发生了这种情况图像颜色总数 http://www.php.net/manual/en/function.imagecolorstotal.php到你的代码:

    $tidx = imagecolortransparent($img);
    $palletsize = imagecolorstotal($img);
    if ($tidx >= 0 && $tidx < $palletsize) {
      $transColor = imagecolorsforindex($img, $tidx);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

什么可能导致 imagecolorsforindex() 出现“颜色索引超出范围”错误? 的相关文章

随机推荐