How to convert a Base64 PNG to a JPG image?

24,835

Solution 1

Base64 is an encoding format that is strictly used to convert data into a text transportable format. Whatever is in that encoding format needs to be converted further if you want another format. So if you want the PNG to be a JPEG, after the Base64 decode it needs to be converted by another tool into a JPEG. This thread has some good suggestions. @Andrew Moore who answers the thread recommends using a function like this. Be sure to have the GD library installed as part of your PHP setup:

// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

So using your code as an example, you would then use this function to do the following:

png2jpg('myDirectory/filename.png','myDirectory/filename.jpg', 100);

Or you can deconstruct the functions of that png2jpg function and use them in your code like this:

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
file_put_contents('myDirectory/filename.png', $data);
$image = imagecreatefrompng('myDirectory/filename.png');
imagejpeg($image, 'myDirectory/filename.jpg', 100);
imagedestroy($image);

Solution 2

The easiest way to to this since PHP 5.2.0, is using the data:// wrapper, you can use it like a file in many of functions.

$image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhE...';
$image = imagecreatefrompng($image);
imagejpeg($image, 'myDirectory/filename.jpg', 100);
imagedestroy($image);
Share:
24,835
Nader Khan
Author by

Nader Khan

Updated on November 07, 2020

Comments

  • Nader Khan
    Nader Khan over 3 years

    I have this Base64 PNG, which I want to decode to JPG. If I convert to PNG it works fine, using:

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);
    file_put_contents('myDirectory/filename.png', $data);
    

    But if I try to save it as JPG, it comes out in black and white using (MyDirectory/filename.jpg).

    How do I convert it to a JPG? here is an example of my Base64 PNG:

    data:image/png;base64,iVBORw0KGgoAAAANSUhE...