imagecolorsforindex()会导致"颜色索引超出范围"错误的原因是什么?

Sau*_*aul 5 php gd image-manipulation imagemagick image-processing

当修补程序调整大量的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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Gus*_*Gus 9

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

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

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

    $tidx = imagecolortransparent($img);
    $palletsize = imagecolorstotal($img);
    if ($tidx >= 0 && $tidx < $palletsize) {
      $transColor = imagecolorsforindex($img, $tidx);
Run Code Online (Sandbox Code Playgroud)