PHP GD - 透明PNG黑色背景

时间:2015-02-19 12:04:51

标签: php transparency gd alpha

我正在使用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);

1 个答案:

答案 0 :(得分:2)

它应该是:

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

有一个类似的问题 here