【问题标题】:PHP GD - transparent PNG black backgroundPHP GD - 透明PNG黑色背景
【发布时间】:2015-04-20 18:32:28
【问题描述】:

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

【问题讨论】:

    标签: php transparency gd alpha


    【解决方案1】:

    应该是这样的:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 2013-03-17
      • 2017-11-13
      • 2015-03-26
      • 2014-06-03
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      相关资源
      最近更新 更多