Voting

: min(five, six)?
(Example: nine)

The Note You're Voting On

Jeff
18 years ago
I came across the problem of having a page where any image could be uploaded, then I would need to work with it as a true color image with transparency. The problem came with palette images with transparency (e.g. GIF images), the transparent parts changed to black (no matter what color was actually representing transparent) when I used imagecopy to convert the image to true color.

To convert an image to true color with the transparency as well, the following code works (assuming $img is your image resource):

<?php
//Convert $img to truecolor
$w = imagesx($img);
$h = imagesy($img);
if (!
imageistruecolor($img)) {
$original_transparency = imagecolortransparent($img);
//we have a transparent color
if ($original_transparency >= 0) {
//get the actual transparent color
$rgb = imagecolorsforindex($img, $original_transparency);
$original_transparency = ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue'];
//change the transparent color to black, since transparent goes to black anyways (no way to remove transparency in GIF)
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
}
//create truecolor image and transfer
$truecolor = imagecreatetruecolor($w, $h);
imagealphablending($img, false);
imagesavealpha($img, true);
imagecopy($truecolor, $img, 0, 0, 0, 0, $w, $h);
imagedestroy($img);
$img = $truecolor;
//remake transparency (if there was transparency)
if ($original_transparency >= 0) {
imagealphablending($img, false);
imagesavealpha($img, true);
for (
$x = 0; $x < $w; $x++)
for (
$y = 0; $y < $h; $y++)
if (
imagecolorat($img, $x, $y) == $original_transparency)
imagesetpixel($img, $x, $y, 127 << 24);
}
}
?>

And now $img is a true color image resource

<< Back to user notes page

To Top