2
  • I am taking a PNG image from a url as below.
  • I want to convert the PNG image to JPEG without saving disk with PHP.
  • Finally I want to assign JPEG image to $content_jpg variable.

     $url = 'http://www.example.com/image.png';
     $content_png = file_get_contents($url);
    
     $content_jpg=;
    
Dulitha K
  • 2,088
  • 1
  • 19
  • 18
  • 1
    What do you mean by 'convert the image?' If you want to edit the image, you don't need to save the image, just output it. See: http://us1.php.net/manual/en/ref.image.php –  Jan 14 '14 at 03:55
  • 1
    I am doing this in Oxwall. After converting I will save jpg image to system generated location. But I want know the possibility of converting png image content($content_png) to jpg without writing to disk.This is possible whit C# as a tutorial I found. – Dulitha K Jan 14 '14 at 04:06
  • @Josh, I want to change the format of image from PNG to JPEG. That is what I want to mean by convert the image' and not the edit image. Thanks – Dulitha K Jan 14 '14 at 12:16
  • @ShankarDamodaran, I will output image to browser. Please let us know if you have any better solution than what we found. Thanks. – Dulitha K Jan 16 '14 at 16:30

2 Answers2

5

Simplified answer is,

// 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();
Dulitha K
  • 2,088
  • 1
  • 19
  • 18
4

You want to use the gd library for this. Here's an example which will take a png image and output a jpeg one. If the image is transparent, the transparency will be rendered as white instead.

<?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);

?>
  • The function imagecreatefrompng can accept urls too. So I have passed url to function instead a file. This code work as expected and it out put JPEG file to browser. Thank you very much Josh. – Dulitha K Jan 15 '14 at 17:55