Use PHP to convert JPEGs to transparent PNG

前端 未结 4 1450
刺人心
刺人心 2020-12-15 01:31

I have a lot of JPEG images that I want to convert to PNG images using PHP. The JPEGs are going to be uploaded by clients so I can\'t trust them to make sure they are in the

相关标签:
4条回答
  • 2020-12-15 02:07

    After a few days of trying different solutions and doing some more research, this is what I found worked for me.

     $image = imagecreatefromjpeg( 'image.jpg' );
     imagealphablending($image, true);
     $transparentcolour = imagecolorallocate($image, 255,255,255);
     imagecolortransparent($image, $transparentcolour)
    

    The imagealphablending($image, true); is important.

    Using imagesavealpha($f, true); as mentioned in a previous answer definitely doesn't work and seems to actually prevent you from making the background transparent...

    To output the transparent image with the correct headers.

    <?php
         header( 'Content-Type: image/png' );
         imagepng( $image, null, 1 );
    ?>
    
    0 讨论(0)
  • 2020-12-15 02:13

    This worked for me:

     $image = imagecreatefromjpeg( "image.jpg" );
     imagealphablending($image, true);
     imagepng($image, "image.png");
    
    0 讨论(0)
  • 2020-12-15 02:14

    I found this solution at Convert jpg image to gif, png & bmp format using PHP

    $imageObject = imagecreatefromjpeg($imageFile);
    imagegif($imageObject, $imageFile . '.gif');
    imagepng($imageObject, $imageFile . '.png');
    imagewbmp($imageObject, $imageFile . '.bmp');
    
    0 讨论(0)
  • 2020-12-15 02:17
    $f = imagecreatefromjpeg('path.jpg');
    $white = imagecolorallocate($f, 255,255,255);
    imagecolortransparent($f, $white);
    

    More details here

    0 讨论(0)
提交回复
热议问题