22

I tried something like this but it just makes the background of the image white, not necessarily the alpha of the image. I wanted to just upload everything as jpg's so if i could somehow "flatten" a png image with some transparently to default it to just be white so i can use it as a jpg instead. Appreciate any help. Thanks.

$old = imagecreatefrompng($upload);
$background = imagecolorallocate($old,255,255,255);
imagefill($old, 0, 0, $background);
imagealphablending($old, false);
imagesavealpha($old, true);
Shawn
  • 313
  • 1
  • 6
  • 16

1 Answers1

68
<?php
$input_file = "test.png";
$output_file = "test.jpg";

$input = imagecreatefrompng($input_file);
$width = imagesx($input);
$height = imagesy($input);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output,  255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
imagejpeg($output, $output_file);
Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
  • I was messing around for ages with this problem, and this answer is perfect and makes such much sense now I've seen it. Thanks a lot. – Jamie Brown May 06 '14 at 23:15
  • 3
    Not sure how much this affects performance, but I'd suggest using `imagesx($input)` and `imagesy($input)` after `imagecreatefrompng()` rather than `getimagesize()`, to avoid reading and parsing headers from the file again. – mindplay.dk Mar 07 '19 at 09:36