This is the part of the code I use to display or resize and display with Cache headers. It works fine for JPG images. But PNG images get added with black background. This type of questions are available in SO and Google but almost the solutions accepted or suggested are same: imagealphablending
– FALSE and imagesavealpha
– TRUE. But in my case, nothing works. What would be the problem?
$image_information=getimagesize($img);
if($image_information['mime']=='image/gif')
{
$img=imagecreatefromgif($img);
$type="gif";
$image_header="image/gif";
}
elseif($image_information['mime']=='image/png')
{
$img=imagecreatefrompng($img);
$type="png";
$image_header="image/png";
}
else
{
$img=imagecreatefromjpeg($img);
$type="jpg";
$image_header="image/jpeg";
}
$width=imagesx($img);
$height=imagesy($img);
if((isset($w))&(!isset($h))) // If Width or Height is posted, calculate the aspect dimensions
{
$h=($height/$width*$w);
}
if((isset($h))&(!isset($w)))
{
$w=(($h*$width)/$height);
}
if(!isset($w))
{
$w=$width;
}
if(!isset($h))
{
$h=$height;
}
$new_image=imagecreatetruecolor($w, $h);
if($type=="gif")
{
$background=imagecolorallocate($new_image, 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($new_image, $background);
}
elseif($type=="png")
{
imagealphablending($new_image, FALSE);
imagesavealpha($new_image, TRUE);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefilledrectangle($new_image, 0, 0, $w, $h, $transparent);
}
imagecopyresampled($new_image,$img,0,0,0,0,$w,$h,$width,$height);
$seconds_to_cache = 864000; // Add cache headers
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control:max-age=$seconds_to_cache, must-revalidate");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header('Content-Type: $image_header');
if($type="jpg")
imagejpeg($new_image, NULL, 75);
elseif($type=="png")
imagepng($new_image, NULL, 75);
elseif($type=="gif")
imagegif($new_image, NULL);
imagedestroy($new_image);
Edit: I saved the image to my system, tried opening in,
- Picasa Photo Viewer – Image opens with Black BG.
- Ms Paint – Image opens with Black BG.
- Photoshop CS6 – Error message pops out: Could not open because of Program error.
2
Answers
You are not saving the alpha channel from your original image.
add
imagealphablending($img, true);
right above the following code
$width=imagesx($img);
$height=imagesy($img);
EDIT:
and then try this
instead of your transparent code with filled rectangle
I would suggest you use a well coded class to do image manipulation. Verot.net’s php class for image upload offers, on top of the upload manipulation, all sorts of image manipulation functionalities in a DRY, well structured API. In the end, your code will be much more portable and futureproof.