-1

When saving an alpha blended image like this:

enter image description here

using imagejpeg(), with the code below, I get a black background.

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

I end up with a black square. That's clearly not what I need, the background should be white.

I read up on alpha blending, tried several things with the GD functions in PHP, but I couldn't get it done. Perhaps I should copy the image to a new image before saving it, but I'd rather not do that.

My question is: What is the simplest way to save the above image with the proper white background using the PHP GD functions? No alpha blending is needed in output, all I want is a white background.

Bonus question: Is there a way to detect whether an image has an alpha channel?

KIKO Software
  • 15,283
  • 3
  • 18
  • 33

2 Answers2

0

I managed to do it when I copy the image with this code:

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

This does solve my problem, but is this copying really needed?

I also still have no way to detect whether an image has an alpha channel.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33
-1

You can using imagealphablending and imagesavealpha for save alpha channel

$imgPng = imagecreatefrompng($strImagePath);
imagealphablending($imgPng, true);
imageSaveAlpha($imgPng, true);

header("Content-type: image/png");
imagepng($imgPng);

About alpha channel, you can analyse pixel for that using imagecolorat. Example of analyse alpha has at comments

Ararat
  • 73
  • 2
  • 11
  • I appreciate your effort to answer my question, but you're not actually answering my main question. Yes, your code would keep the alpha channel, but that's not what I want. The example image would be better off staying a PNG, but it is just an example, I want to output a JPEG image without an alpha channel, but with a white background where the original image is transparent. And yes, the alpha channel can be accessed with `imagecolorat`, but that's hardly an ideal way to detect the presence of such a channel. – KIKO Software Apr 15 '20 at 15:50