Magento 2 is an insanely flexible platform. However, at some point, you can face issues like the PNG image format is not supported in the pdf files in Magento 2 store.
I’ll come to that point later, first, let’s understand the difference between JPG and PNG image format and which is the better option.
JPG file format:
- Smaller file size
- Improves the speed performance
- Better for website and sharing
PNG fIle format
- Larger file size
- Lossless image quality
When we talk about Magento 2, the platform doesn’t support the PNG file formats in the PDF files. For example, you want to add the barcode image in the catalog PDF file or invoice PDF file.
The default Magento 2 does not allow the same. Hence, I have come up with a solution to programmatically convert PNG to JPG in Magento 2 store.
Method to programmatically convert PNG to JPG in Magento 2:
//$ext == 'jpg'; //$path == 'full path of image'; //$name == 'image name with extension'; //$newname == 'newimage'; public function convert($ext, $path, $name, $newname = NULL) { $exploded = explode('.', $name); $extoriginal = $exploded[sizeof($exploded) - 1]; switch ($extoriginal) { case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($path . $name); break; case 'png': $image = imagecreatefrompng($path . $name); break; } $bg = imagecreatetruecolor(imagesx($image), imagesy($image)); imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255)); imagealphablending($bg, TRUE); imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); imagedestroy($image); $quality = 100; $newname = ($newname == NULL) ? $exploded[0] : $newname; switch ($ext) { case 'jpg': case 'jpeg': $newimage = $path . $newname . ".jpg"; imagejpeg($bg, $newimage, $quality); break; case 'png': $newimage = $path . $newname . ".png"; imagepng($bg, $newimage, $quality); break; } imagedestroy($bg); return $newimage; }
That’s it.
Please share the solution with fellow developers via social media.
Thank you.