【问题标题】:Set background color on an alpha blended image在 Alpha 混合图像上设置背景颜色
【发布时间】:2020-07-28 04:35:18
【问题描述】:

像这样保存 alpha 混合图像时:

使用imagejpeg(),使用下面的代码,我得到黑色背景。

$sourcePath = "<path to the image above>";
$destPath = "<path to where I want to store it>";
$image = imagecreatefrompng($sourcePath);
imagejpeg($image, $destPath, 85);

我最终得到一个黑色方块。这显然不是我需要的,背景应该是白色的。

我阅读了有关 alpha blending 的内容,并尝试了几件事与 PHP 中的 GD 函数,但我无法完成。也许我应该在保存之前将图像复制到新图像,但我不想这样做。

我的问题是: 使用 PHP GD 函数以适当的白色背景保存上述图像的最简单方法是什么?输出中不需要 alpha 混合,我想要的只是白色背景。

额外问题: 有没有办法检测图像是否具有 alpha 通道?

【问题讨论】:

    标签: php image-processing gd alphablending


    【解决方案1】:

    当我使用此代码复制图像时,我设法做到了:

    // start with the same code as in the question
    $sourcePath = "<path to the image above>";
    $destPath   = "<path to where I want to store it>";
    $image      = imagecreatefrompng($sourcePath);
    // get image dimensions 
    $width      = imagesx($image);
    $height     = imagesy($image);
    // create a new image with the same dimensions
    $newImage   = imagecreatetruecolor($width, $height);
    // get white in the new image
    $white      = imagecolorallocate($newImage, 255, 255, 255);
    // and fill the new image with that
    imagefilledrectangle($newImage, 0, 0, $width, $height, $white);
    // now copy the alpha blended image over it
    imagecopy($newImage, $image, 0, 0, 0, 0, $width, $height);
    // and finally the jpeg output
    imagejpeg($newImage, $destPath, 85);
    

    这确实解决了我的问题,但真的需要这种复制吗?

    我仍然无法检测图像是否具有 alpha 通道。

    【讨论】:

      【解决方案2】:

      您可以使用imagealphablendingimagesavealpha 来保存Alpha 通道

      $imgPng = imagecreatefrompng($strImagePath);
      imagealphablending($imgPng, true);
      imageSaveAlpha($imgPng, true);
      
      header("Content-type: image/png");
      imagepng($imgPng);
      

      关于 Alpha 通道,您可以使用 imagecolorat 分析像素。在 cmets 分析 alpha 的示例

      【讨论】:

      • 感谢您为回答我的问题所做的努力,但您实际上并没有回答我的主要问题。是的,您的代码会保留 alpha 通道,但这不是我想要的。示例图像最好保留PNG,但这只是一个示例,我想输出一个没有alpha通道的JPEG图像,但原始图像是透明的白色背景。是的,可以使用imagecolorat 访问 alpha 通道,但这并不是检测此类通道是否存在的理想方法。
      猜你喜欢
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 2012-06-04
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      相关资源
      最近更新 更多