使用PHP将JPEG转换为透明PNG [英] Use PHP to convert JPEGs to transparent PNG

查看:364
本文介绍了使用PHP将JPEG转换为透明PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多JPEG图像,我想使用PHP转换为PNG图像. JPEG将由客户上载,所以我不信任他们以确保它们的格式正确.

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.

PHP是否可以使用任何功能来实现这一目标?

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

推荐答案

经过几天的尝试,尝试了不同的解决方案并进行了更多研究, 这就是我发现对我有用的.

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)

imagealphablending($image, true);很重要.

使用上一个答案中提到的imagesavealpha($f, true);绝对无效,并且似乎实际上使您无法透明背景...

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

这篇关于使用PHP将JPEG转换为透明PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆