Use PHP to convert JPEGs to transparent PNG

本小妞迷上赌 提交于 2019-12-18 12:06:43

问题


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 right format.

I also want to make their white backgrounds transparent.

Does PHP have any functions I can use to achieve this?


回答1:


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



回答2:


$f = imagecreatefromjpeg('path.jpg');
$white = imagecolorallocate($f, 255,255,255);
imagecolortransparent($f, $white);

More details here




回答3:


This worked for me:

 $image = imagecreatefromjpeg( "image.jpg" );
 imagealphablending($image, true);
 imagepng($image, "image.png");



回答4:


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


来源:https://stackoverflow.com/questions/7610128/use-php-to-convert-jpegs-to-transparent-png

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