Convert image format PNG to JPEG without saving to

2020-02-15 03:42发布

  • 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=;
    

标签: php gdlib
2条回答
小情绪 Triste *
2楼-- · 2020-02-15 04:00

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();
查看更多
够拽才男人
3楼-- · 2020-02-15 04:23

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

?>
查看更多
登录 后发表回答