PHP GD-透明PNG黑色背景 [英] PHP GD - transparent PNG black background

查看:598
本文介绍了PHP GD-透明PNG黑色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和GD裁剪并输出带有以下代码的图像。它工作正常,但是当我将透明PNG传递给它时,会生成黑色背景。我该如何阻止呢?

I am using PHP and GD to crop and output an image with the code below. it works fine but when i pass a transparent PNG into it i get a black background generated. How can i stop this?

//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);


推荐答案

应该类似于:

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;
}

有一个类似的问题 此处

There is a similar question here

这篇关于PHP GD-透明PNG黑色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆