我有一段代码,
它的想法是创建一个定义的高度/宽度的透明画布,所以我可以在那里放置一个jpg / png / gif。
但是,如果它将PNG放在透明的地方,则需要保留透明度。
这是代码的示例
header("Content-type: image/png");
$canvas = imagecreatetruecolor($maxWidth, $maxHeight);
$image = $_GET['file'];
$leftOffset = ($maxWidth / 2) - ($width / 2);
$topOffset = ($maxHeight / 2) - ($height / 2);
$quality = (isset($_GET['quality'])) ? (int) ceil($_GET['quality'] / 10) : ceil($DEFAULT_QUALITY / 10);
$quality = $quality == 10 ? 9 : $quality;
switch($mime){
case "image/jpeg":
$image = imagecreatefromjpeg($image);
$red = imagecolorallocate($canvas, 0, 255, 0);
imagecolortransparent($canvas, $red);
imagefill($canvas, 0, 0 ,$red);
break;
case "image/gif":
$image = imagecreatefromgif($image);
break;
case "image/png":
$background = imagecolorallocate($canvas, 255, 0, 0);
imagecolortransparent($canvas, $background);
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
$image = imagecreatefrompng($image);
break;
}
imagecopyresampled($canvas, $image, $leftOffset, $topOffset, 0, 0, $width, $height, $width, $width);
imagepng($canvas, null, $quality);
imagedestroy($canvas);
然而问题是,画布仍然是黑色,而图像周围的框区域是透明的。
下图显示了这一点,Lime绿色是身体{background:lime;}所以你可以看到透明区域
我尝试在imagecreatetruecolor
之后使用透明色$red = imagecolorallocate($canvas, 255, 0, 0);
imagecolortransparent($canvas, $red);
imagefill($canvas, 0, 0 ,$red);
如果.png具有淡入淡出效果,则会在其周围产生令人讨厌的红色光晕,其颜色不再精确为255,0,0
有什么建议吗?
由于
答案 0 :(得分:0)
这对你有用!
<?
$image = "your_image.png";
$image_info = getimagesize($image);
$width = $image_info[0];
$height = $image_info[1];
$mime_type = $image_info["mime"];
$maxWidth = 250;
$maxHeight = 250;
$quality = 9;
header("Content-type: $mime_type");
$canvas = imagecreatetruecolor($maxWidth, $maxHeight);
imagealphablending($canvas, false);
$background = imagecolorallocatealpha($canvas, 255, 255, 255, 127);
imagefilledrectangle($canvas, 0, 0, $maxWidth, $maxHeight, $background);
imagealphablending($canvas, true);
$leftOffset = ($maxWidth / 2) - ($width / 2);
$topOffset = ($maxHeight / 2) - ($height / 2);
switch($mime_type)
{
case "image/jpeg":
//JPG code
break;
case "image/gif":
//GIF code
break;
case "image/png":
$new_image = imagecreatefrompng($image);
imagecopyresampled($canvas, $new_image, $leftOffset, $topOffset, 0, 0, $width, $height, $width, $height);
imagealphablending($canvas, true);
imagesavealpha($canvas, true);
imagepng($canvas, null, $quality);
imagedestroy($canvas);
break;
}
?>