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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3