3

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);
odd_duck
  • 3,941
  • 7
  • 43
  • 85

2 Answers2

5

It should be something along the lines of:

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

Community
  • 1
  • 1
cch
  • 3,336
  • 8
  • 33
  • 61
0

In my case, the alpha channel was already configured correctly and blending seemed to be disabled. All I had to do was add this line before outputting the image:

imagesavealpha($image_obj, true);

After that my PNGs had the transparent background I was expecting.

Matt N.
  • 53
  • 1
  • 10