doujian3132 2015-10-22 20:01
浏览 426

PNG和GIF透明度丢失了

I am having a problem working with images and php.

I am using a function with which will resize an image according to my limitations and then create a new image.

The problem is when I have a png or gif file to resize, the transparency gets lost generating images with black background.

Here is the function:

// 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条回答 默认 最新

  • dongtao5104 2015-10-22 20:08
    关注

    You are always using imagejpeg no matter what extension you get, there is also imagepng and imagegif. You should use those if you have a .gif or .png

    I'm talking about this line:

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

    You should call imagejpeg, imagepng or imagegif depending the file type.

    评论

报告相同问题?

悬赏问题

  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑