Reputation: 11780
I use the below code to resize images (jpg, png, gif). The code is working perfectly. But the problem is after resizing the images, all transparent images (both png and gif) have a black background.
How can I maintain the transparency so that resized images will have not have black background?
$target = 'uploads/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);;
$filename=$newname;
if($ext=='jpg'||$ext=='jpeg') {
$im = imagecreatefromjpeg('uploads/'.$filename);
} else if ($ext=='gif') {
$im = imagecreatefromgif('uploads/'.$filename);
} else if ($ext=='png') {
$im = imagecreatefrompng('uploads/'.$filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nm = imagecreatetruecolor(400, 300);
imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
imagejpeg($nm, 'thumbnails/' . $filename);
Upvotes: 0
Views: 2483
Reputation: 104
I also had similar troubles where a black background still appeared when using:
imagealphablending($image, false);
imagesavealpha($image, true);
I found the below combination to be successful though:
imagecolortransparent($image, imagecolorallocate($thumbnail, 0, 0, 0));
imagealphablending($image, false);
Upvotes: 1
Reputation: 1098
imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.
You have to unset alphablending (imagealphablending($im, false)), to use it.
Try adding
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
Here:
.
.
$nm = imagecreatetruecolor(400, 300);
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
.
.
Also consider using imagecopyresampled instead of imagecopyresized.
imagecopyresampled() smoothly interpolates pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.
Use imagecopyresampled($nm, $im, 0,0,0,0,400,300,$ox,$oy);
Instead of
imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
Upvotes: 1