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

不打扰是莪最后的温柔 提交于 2019-12-29 09:18:09

问题


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


来源:https://stackoverflow.com/questions/21105802/convert-image-format-png-to-jpeg-without-saving-to-disk-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!