简体   繁体   English

减少png图片的大小而不会失去透明度

[英]Reduce size of png image without losing transparency

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? 如何在不损失透明度的情况下缩小png图像?

 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 : 更改并在compress函数中添加几行:

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. 重要的是要理解为什么当png时图像会变成黑色背景,这就是由于透明度。 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. JPEG格式不允许具有透明图像,只有PNG格式支持它,因此在每种情况下调用正确的函数都是唯一的问题。

This script should work fine , if previously was working. 如果以前可以运行,此脚本应该可以正常运行。 Please try it. 请尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM