- 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=;
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);
?>
回答2:
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();