PNG和GIF透明度丢失了

时间:2015-10-22 20:01:56

标签: php image resize transparency

我在使用图片和php时遇到问题。

我正在使用一个函数,根据我的限制调整图像大小,然后创建一个新图像。

问题是当我有一个png或gif文件来调整大小时,透明度会因为生成黑色背景的图像而丢失。

这是功能:

// Resize image - preserve ratio of width and height.
function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 70)
{
    // Obtain image from given source file.
    $info = getimagesize($sourceImage);
    $imgtype = image_type_to_mime_type($info[2]);

    switch ($imgtype) {
      case 'image/jpeg':
        $image = imagecreatefromjpeg($sourceImage);
      break;
      case 'image/png':
        $image = imagecreatefrompng($sourceImage);
      break;
      default:
        die('Invalid image type.');
    }

    // Get dimensions of source image.
    list($origWidth, $origHeight) = getimagesize($sourceImage);

    if ($maxWidth == 0)
    {
        $maxWidth  = $origWidth;
    }

    if ($maxHeight == 0)
    {
        $maxHeight = $origHeight;
    }

    // Calculate ratio of desired maximum sizes and original sizes.
    $widthRatio = $maxWidth / $origWidth;
    $heightRatio = $maxHeight / $origHeight;

    // Ratio used for calculating new image dimensions.
    $ratio = min($widthRatio, $heightRatio);

    // Calculate new image dimensions.
    $newWidth  = (int)$origWidth  * $ratio;
    $newHeight = (int)$origHeight * $ratio;

    // Create final image with new dimensions.
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
    imagejpeg($newImage, $targetImage, $quality);

    // Free up the memory.
    imagedestroy($image);
    imagedestroy($newImage);

    return true;
}

2 个答案:

答案 0 :(得分:0)

无论您使用哪种扩展程序,您始终都在使用imagejpeg,还有imagepngimagegif。如果你有.gif或.png

,你应该使用它们

我在谈论这一行:

imagejpeg($newImage, $targetImage, $quality);

您应该根据文件类型致电imagejpegimagepngimagegif

答案 1 :(得分:0)

除了以支持透明度的格式保存图像外,还需要指示GD复制来自源的透明度信息。对于PNG-8和GIF,您必须手动复制并设置从源到目的地的透明色(请参阅imagecolortransparent),对于PNG-24,您必须保存Alpha通道(请参阅imagesavealpha)。

相关问题