我在下面有这个功能,允许我调整上传的图像的大小,
function resize_image($image,$width,$height,$scale)
{
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType)
{
case "image/gif":
$source = imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source = imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source = imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType)
{
case "image/gif":
imagegif($newImage,$image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$image,90);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$image);
break;
}
chmod($image, 0777);
return $image;
}
但是这个函数有一个问题就是当我有一个png或一个透明背景的gif时它无法创建透明度。
如何修复此功能以允许透明与PHP?
答案 0 :(得分:4)
这是我的答案,
# This is the resizing/resampling/transparency-preserving magic
if ( ($imageType == "image/gif") || ($imageType == "image/png") )
{
$transindex = imagecolortransparent($source);
if($transindex >= 0)
{
$transcol = imagecolorsforindex($source, $transindex);
$transindex = imagecolorallocatealpha($newImage, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
imagefill($newImage, 0, 0, $transindex);
imagecolortransparent($newImage, $transindex);
}
elseif ($imageType == "image/png" || $imageType == "image/x-png")
{
imagealphablending($newImage, false);
$color = imagecolorallocatealpha($newImage, 0, 0, 0, 127);
imagefill($newImage, 0, 0, $color);
imagesavealpha($newImage, true);
}
}
答案 1 :(得分:3)
我发现这个解决方案非常有用!
http://www.php.net/manual/ru/function.imagecopyresampled.php#104028
您只需在imagecreatetruecolor()和imagecopyresampled()之间添加此代码即可。不要忘记定义$ type。
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
// preserve transparency
if($type == "gif" || $type == "png"){
imagecolortransparent($newImage, imagecolorallocatealpha($newImage, 0, 0, 0, 127));
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
}
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
答案 2 :(得分:1)
查看一个开源的smart_resize_image方法,它们会检查imagecolortransparent
,如果存在,则会将其重新应用到新图像。
值得一看,在github上查看该项目,而不是重新发明轮子。还可以让您深入了解他们是如何做到这一点的,并且是努力协作的工作(很多人围绕已知的[和未知的]错误工作)。
答案 3 :(得分:0)
为了让GD Lib绘制透明度,您必须定义透明色。您可以在图形上的某处对颜色进行采样并使用它。
http://www.php.net/manual/en/function.imagecolortransparent.php