Reputation: 11
I have a PNG image with transparent background, I want to create Progressive JPEG with a white background, any workaround is really appreciated and is that right to create PJPEG from PNG?
below is my workaround, I just want to know is this really right approach to proceed.
$filePath = 'a.png';
$savePath = 'a.jpeg';
$colorRgb = array('red' => 255, 'green' => 255, 'blue' => 255);
$img = @imagecreatefrompng($filePath);
$width = imagesx($img);
$height = imagesy($img);
$backgroundImg = @imagecreatetruecolor($width, $height);
$color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
imagefill($backgroundImg, 0, 0, $color);
imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height);
imageinterlace($backgroundImg, 1);
imagejpeg($backgroundImg, $savePath, 80);
Upvotes: 1
Views: 951
Reputation: 216
This is what is tried once in my project hope it helps:
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im === false) {
die("imagecreatefromstring failed");
}
imageinterlace($im, true);
imagejpeg($im, 'new.jpg');
imagedestroy($im);
Upvotes: 0
Reputation: 423
header('Content-Type: image/jpeg');
$image = new Imagick();
$image->readImage("image.png"); //add your png file
$image->setImageBackgroundColor('#FFFFFF'); //add your background color
$image = $image->flattenImages(); //flatten the image
$image->setImageFormat('jpg'); //set the format
$image->writeImage('image.jpg'); //save it
echo $image;
Using Imagick will simply do the job :)
NOTE: add extension=imagick.so
in your php.ini, if Imagick is not enabled by default.
Upvotes: 1