I have a script that uploads and resizes images using the GD library and PHP. I now want to upload a PNG image and for it to be stored as PNG and JPEG, I am then going to resize it but that's fine.
The problem I'm having is that sometimes, the converted version of the image (jpg) is distorted. Other times it is fine.
My code is taken from another answer here on StackOverflow:
function png2jpg($originalFile, $outputFile, $quality){
$image = imagecreatefrompng($originalFile);
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
}
An example of the distorted result is shown below, I am fully aware that I won't get the transparency on the JPG, I just want a white background. Any ideas?
I can't post images, so link to original: http://private.granvilleoil.com/prodImages/large/Petro-Patch.png) and JPG: http://private.granvilleoil.com/prodImages/large/Petro-Patch.jpg)
You need to create a fresh image with a white (or whatever you want) background and copy the none-transparent pixels from the png to that image:
function png2jpg($originalFile, $outputFile, $quality) {
$source = imagecreatefrompng($originalFile);
$image = imagecreatetruecolor(imagesx($source), imagesy($source));
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
imagecopy($image, $source, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, $outputFile, $quality);
imagedestroy($image);
imagedestroy($source);
}