1

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);
Anand
  • 11
  • 6
  • Welcome to [Stack Overflow](http://stackoverflow.com/) ! Please read [How to Ask Question](http://stackoverflow.com/help/how-to-ask) and provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) ! – Saurabh Bhandari Mar 09 '17 at 11:58
  • 1
    check out [imagemagick](https://coderwall.com/p/ryzmaa/use-imagemagick-to-create-optimised-and-progressive-jpgs) to do this. Also this [SO post](http://stackoverflow.com/questions/26874586/photoeffects-site-based-on-php/) will show you many php libraries to get the job done. – Niket Pathak Mar 09 '17 at 12:01
  • Thank you! @NiketPathak, will look other options. – Anand Mar 09 '17 at 12:20
  • @Anand Use ***Imagick*** function of PHP. Its the simple image modifier for PHP. http://php.net/manual/en/book.imagick.php – Shamshid Mar 09 '17 at 12:58
  • @SaurabhBhandari : can you please take a look at the detail question and let me know your thoughts? – Anand Mar 09 '17 at 12:58

2 Answers2

1
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.

Shamshid
  • 403
  • 3
  • 11
  • You might want to add that ImageMagick is not necessarily part of a default PHP installation and usually needs to be installed manually - or is that not the case anymore? – domsson Mar 09 '17 at 13:27
  • @domdom it is enabled by default I guess. If not adding `extension=imagick.so` in php.ini will solve the issue – Shamshid Mar 09 '17 at 13:36
0

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);
Abizz
  • 216
  • 2
  • 16