0

我有一段代码,

它的想法是创建一个具有定义高度/宽度的透明画布,因此我可以在其中放置 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);

然而问题是,画布仍然是黑色的,而图像周围的框区域是透明的。

下图演示了这一点,石灰绿色是主体 {背景:石灰;},因此您可以看到透明区域

在此处输入图像描述

我尝试在 imagecreatetruecolor 之后使用透明颜色

$red = imagecolorallocate($canvas, 255, 0, 0);
imagecolortransparent($canvas, $red);
imagefill($canvas, 0, 0 ,$red);

如果 .png 具有淡入淡出效果,它会在其周围发出令人讨厌的红色光芒,其中颜色不再是 255、0、0

有什么建议么?

谢谢

4

1 回答 1

1

这应该适合你!

<?
$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;
}
?>
于 2013-07-27T16:33:08.130 回答