Search code examples
phpgd

Convert JPEG to a Progressive JPEG in PHP


I'm trying to re-save an already created JPEG as a progressive jpg.

Basically, on the front end I have some JS that crops an image, and outputs a base64 image JPEG. Once it is passed to the PHP script, I create it as a regular JPEG file, like so:

$largeTEMP = explode(',', $_POST['large']);
$large = base64_decode($largeTEMP[1]);
file_put_contents('../../images/shows/'.$dirName.'/large.jpg', $large);

I'm wanting this jpg image to be progressive, so I was looking around and found the PHP function imageinterlace; however, I can't seem to get it to work. I've tried various combinations, but I feel like I'm going about this in the wrong way for some reason.

So my question is, how can I take my already generated JPEG and convert it to be progressive using PHP? Or, better yet, convert it to a progressive JPEG before I even save it in the first place.


Solution

  • Create image resource with imagecreatefromstring:

    $data = base64_decode($data);
    $im = imagecreatefromstring($data);
    if ($im === false) {
      die("imagecreatefromstring failed");
    }
    imageinterlace($im, true);
    imagejpeg($im, 'new.jpg');
    imagedestroy($im);