How to check if an image has transparency using GD?

后端 未结 8 1413
耶瑟儿~
耶瑟儿~ 2020-12-09 18:48

How do I check if an image has transparent pixels with php\'s GD library?

8条回答
  •  情书的邮戳
    2020-12-09 19:19

    It doesn't look like you can detect transparency at a glance.

    The comments on the imagecolorat manual page suggest that the resulting integer when working with a true-color image can actually be shifted four times total, with the fourth being the alpha channel (the other three being red, green and blue). Therefore, given any pixel location at $x and $y, you can detect alpha using:

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

    An $alpha of 127 is apparently completely transparent, while zero is completely opaque.

    Unfortunately you might need to process every single pixel in the image just to find one that is transparent, and then this only works with true-color images. Otherwise imagecolorat returns a color index, which you must then look up using imagecolorsforindex, which actually returns an array with an alpha value.

提交回复
热议问题