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);
source share