Png black background when upload and resize image
13,340
Solution 1
I think this link will answer your question: http://www.php.net/manual/pl/function.imagecopyresampled.php#104028
In your code the answer will be something like:
// preserve transparency
if($ext == "gif" or $ext == "png"){
imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127));
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
}
Paste this before executing imagecopyresampled
.
Solution 2
If you did want to save to a JPEG rather than saving to a PNG, you can just change the background colour of the target image to white before you do the copy:
$tmp = imagecreatetruecolor($new_width,$new_height);
imagefilledrectangle($tmp, 0, 0, $new_width, $new_height, imagecolorallocate($tmp, 255, 255, 255));
imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height);
Then you'll end up with a JPEG without any transparency, but the background colour will be white rather than black.
Author by
brook_river
Updated on June 14, 2022Comments
-
brook_river almost 2 years
Can you help me with my code in php?
I don't know how make my pictures transparent. They have black background after the uploading. I have the code here. (and some text for small post and content)
Thhank you.
<?php function zmensi_obrazok($image_max_width, $image_max_height, $obrazok, $obrazok_tmp, $obrazok_size, $filename){ $postvars = array( "image" => $obrazok, "image_tmp" => $obrazok_tmp, "image_size" => $obrazok_size, "image_max_width" => $image_max_width, "image_max_height" => $image_max_height ); $valid_exts = array("jpg","jpeg","png"); $ext = end(explode(".",strtolower($obrazok))); if($postvars["image_size"] <= 1024000){ if(in_array($ext,$valid_exts)){ if($ext == "jpg" || $ext == "jpeg"){ $image = imagecreatefromjpeg($postvars["image_tmp"]); } else if($ext == "png"){ $image = imagecreatefrompng($postvars["image_tmp"]); } list($width,$height) = getimagesize($postvars["image_tmp"]); $old_width = imagesx($image); $old_height = imagesy($image); $scale = min($postvars["image_max_width"]/$old_width, $postvars["image_max_height"]/$old_height); $new_width = ceil($scale*$old_width); $new_height = ceil($scale*$old_height); $tmp = imagecreatetruecolor($new_width,$new_height); imagecopyresampled($tmp,$image,0,0,0,0,$new_width,$new_height,$width,$height); imagejpeg($tmp,$filename,100); return ""; imagedestroy($image); imagedestroy($tmp); } } } ?>