将图像转换为jpg和透明度

时间:2013-01-27 19:28:42

标签: php

我有脚本:

$path = "uploads/";

$img = $_FILES['photoimg']['tmp_name'];
$dst = $path . $_FILES['photoimg']['name'];

if (($img_info = getimagesize($img)) === FALSE)
  die("Image not found or not an image");

$width = $img_info[0];
$height = $img_info[1];

switch ($img_info[2]) {
  case IMAGETYPE_GIF  : $src = imagecreatefromgif($img);  break;
  case IMAGETYPE_JPEG : $src = imagecreatefromjpeg($img); break;
  case IMAGETYPE_PNG  : $src = imagecreatefrompng($img);  break;
  default : die("Unknown filetype");
}

$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $width, $height, $width, $height);
imagejpeg($tmp, $dst.".jpg");

How to convert uploaded images always into JPG format?

这个工作完美,但如果文件是png并且具有透明度,那么我的新图像具有黑色背景。我能改变这种颜色吗?我想要有白色背景。

1 个答案:

答案 0 :(得分:3)

打开透明度

$src = imagecreatefrompng($img);
imagealphablending($src, true);

创建空文件时,请用白色背景填充(默认空图像为黑色)

$tmp = imagecreatetruecolor($width, $height);
imagefill($tmp, 0, 0, imagecolorallocate($tmp, 255, 255, 255));
相关问题