How to convert a Base64 PNG to a jpg image?

I have this Base64 PNG that I want to decode in 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 a JPG, it will exit in black and white ( MyDirectory/filename.jpg ).

How do i convert it to jpg? here is an example of my Base64 PNG:

 data:image/png;base64,iVBORw0KGgoAAAANSUhE... 
+4
source share
2 answers

Base64 is an encoding format that is strictly used to convert data to a portable text format. Regardless of what encoding needs to be converted in this format, if a different format is required. Therefore, if you want PNG to be JPEG, after decoding Base64, you need to convert it with another tool to JPEG. There are some good suggestions in this thread . @Andrew Moore, who answers the question, recommends using such a function. Make sure the GD library is installed as part of your PHP installation:

 // 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 should use this function to do the following:

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

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

 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); 
+8
source

The easiest way to do this, since PHP 5.2.0, uses data: // wrapper, you can use it as a file in many functions.

 $image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhE...'; $image = imagecreatefrompng($image); imagejpeg($image, 'myDirectory/filename.jpg', 100); imagedestroy($image); 
+5
source

All Articles