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

后端 未结 2 1043
春和景丽
春和景丽 2020-12-21 13:28
  • 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

相关标签:
2条回答
  • 2020-12-21 13:47

    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();
    
    0 讨论(0)
  • 2020-12-21 13:49

    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);
    
    ?>
    
    0 讨论(0)
提交回复
热议问题