PHP resized image gives black background

I use this code to resize:

<?php // Function for resizing any jpg, gif, or png image files function ak_img_resize($target, $newcopy, $w, $h, $ext) { list($w_orig, $h_orig) = getimagesize($target); $scale_ratio = $w_orig / $h_orig; if (($w / $h) > $scale_ratio) { $w = $h * $scale_ratio; } else { $h = $w / $scale_ratio; } $img = ""; $ext = strtolower($ext); if ($ext == "gif"){ $img = imagecreatefromgif($target); } else if($ext =="png"){ $img = imagecreatefrompng($target); } else { $img = imagecreatefromjpeg($target); } $tci = imagecreatetruecolor($w, $h); // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h) imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig); imagejpeg($tci, $newcopy, 80); } ?> 

But every time I upload a transparent png image, it turns out with a black background. How to prevent this and maintain a background of transparency?

+4
source share
3 answers

try this before imagecopyresampled, add alpha blending and then save alpa

 imagealphablending($tci, false); imagesavealpha($tci,true); $transparent = imagecolorallocatealpha($tci, 255, 255, 255, 127); imagefilledrectangle($tci, 0, 0, $w, $h, $transparent); 
+4
source

Try setting a transparent color using imagecolortransparent:

http://il.php.net/manual/en/function.imagecolortransparent.php

0
source

Try this to make your resize function

 <?php $file_name =testimg.jpg // your file name extension= explode(".", strtolower($file_name));//get ext of your image if($extension[1]=="jpg" || $extension[1]=="jpeg" ) { $src = imagecreatefromjpeg($filename); // Check ext and set src } else if($extension[2]=="png") { $src = imagecreatefrompng($filename); // Check ext and set src } else { $src = imagecreatefromgif($filename); // Check ext and set src } list($width,$height)=getimagesize($filename); $newwidth=round($width/10); //resized image width $newheight=round($height/10); //resized image height $tmp=imagecreatetruecolor($newwidth,$newheight); imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); $resizedfile = "resizeduploads/". $name; if($extension[1]=="jpg" || $extension[1]=="jpeg" ) { imagejpeg($tmp,$resizedfile); } else if($extension[1]=="png") { imagepng($tmp,$resizedfile); } else { imagegif($tmp,$resizedfile); } imagedestroy($src); imagedestroy($tmp); 
0
source

Source: https://habr.com/ru/post/1403440/


All Articles