I am trying to reduce image size by using the following function. But when I use an image that has transparency, this function repeats the image in transparency pixels and makes distortions. How can I reduce png image without losing transparency?
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
else if ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
else if ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = 'source.png';
$destination_img = 'destination.png';
$d = compress($source_img, $destination_img, 90);
Change and add a couple of lines to your compress function :
function compress($source, $destination, $quality)
{
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source);
imagejpeg($image, $destination, $quality); //Compress with jpg
else if ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source);
else if ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source);
imagepng($image, $destination, $quality); //Compress with png !!
return $destination;
}
$source_img = 'source.png';
$destination_img = 'destination.png';
$d = compress($source_img, $destination_img, 90);
Its important understand why the image gets with black background color when is a png , thats due to the transparency. JPEG format doesn't allow you to have a image with transparency , only PNG format supports it, so its only matter of call the right function in every case.
This script should work fine , if previously was working. Please try it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.