PHP GD - 透明PNG黑色背景

3

我正在使用PHP和GD来裁剪并输出一张图片,以下是代码。它可以正常工作,但是当我传递一个透明的PNG图像时,会生成黑色背景。我该如何解决这个问题?

//setup
switch ($source_type) {
    case IMAGETYPE_JPEG:    $source = imagecreatefromjpeg($img_path);   break;
    case IMAGETYPE_PNG:     $source = imagecreatefrompng($img_path);    break;
}

// setup cropped destination
$cropped = imagecreatetruecolor($cropped_width, $cropped_height);

// create cropped image
$x = (($source_width / 100) * IMAGE_X) - ($cropped_width / 2);
$y = (($source_height / 100) * IMAGE_Y) - ($cropped_height / 2);
imagecopy(
    $cropped,
    $source,
    0, 0,
    $x, $y,
    $cropped_width, $cropped_height
);

// output inc header
header('Content-type: image/jpeg');
imagejpeg($cropped);
2个回答

5
它应该是类似于以下内容:
switch ($source_type)
{
 case IMAGETYPE_PNG:

    $background = imagecolorallocate($source, 0, 0, 0);
    // remove the black 
    imagecolortransparent($source, $background);

    // turn off alpha blending
    imagealphablending($source, false);


    imagesavealpha($source, true);

    break;
}

这里有一个类似的问题:链接

0
在我的情况下,Alpha 通道已经正确配置,并且混合似乎被禁用了。我所要做的就是在输出图像之前添加这行代码:
imagesavealpha($image_obj, true);

然后我的PNG文件拥有了我所期望的透明背景。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接