Black Png background when loading and resizing images

Can you help me with my php code?

I do not know how to make my photos transparent. After loading, they have a black background. I have a code here. (and some text for a little message and content)

Help.

<?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); } } } ?> 
+4
source share
2 answers

I think this link will answer your question: http://www.php.net/manual/pl/function.imagecopyresampled.php#104028

In your code, the answer will look something like this:

 // preserve transparency if($ext == "gif" or $ext == "png"){ imagecolortransparent($tmp, imagecolorallocatealpha($tmp, 0, 0, 0, 127)); imagealphablending($tmp, false); imagesavealpha($tmp, true); } 

Insert this before executing imagecopyresampled .

+4
source

If you want to save to JPEG instead of saving to PNG, you can simply change the background color of the target image to white before making a 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 will get a JPEG without any transparency, but the background color will be white, not black.

+1
source

All Articles