Convert PNG image format to JPEG without saving to disk - PHP

  • I am taking the PNG image from the URL as shown below.
  • I want to convert a PNG image to JPEG without saving a PHP disc.
  • Finally, I want to assign the JPEG image to the variable $ content_jpg.

     $url = 'http://www.example.com/image.png';
     $content_png = file_get_contents($url);
    
     $content_jpg=;
    
+1
source share
2 answers

For this you want to use the gd library . Here is an example that will take a png image and output jpeg. If the image is transparent, the transparency will be displayed as white.

<?php

$file = "myimage.png";

$image = imagecreatefrompng($file);
$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);

header('Content-Type: image/jpeg');

$quality = 50;
imagejpeg($bg);
imagedestroy($bg);

?>
+4
source

Simplified answer:

// PNG image url
$url = 'http://www.example.com/image.png';

// Create image from web image url
$image = imagecreatefrompng($url);

// Start output buffer
ob_start(); 

// Convert image
imagejpeg($image, NULL,100);
imagedestroy($image);

// Assign JPEG image content from output buffer
$content_jpg = ob_get_clean();
+5
source

All Articles