PHP/GD:如何处理jpg透明度? [英] PHP/GD: How to handle jpg transparency?

查看:82
本文介绍了PHP/GD:如何处理jpg透明度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPG不支持透明度.

JPG doesn't support transparency.

但是,您可以从GIMP等导出具有透明区域的图像.在这种情况下,透明区域将在您的浏览器,Windows资源管理器或其他软件中显示为黑色或白色.

Yet you can export an image with transparent areas from for example GIMP. In that case the transparent areas will show either black or white in your browser, Windows explorer or other software.

我经常收到需要处理并以几种较小格式提供的此类文件.我通过使用GD库的一些PHP脚本来做到这一点.问题在于,这些区域在处理后的版本中会变成黑色还是白色,这是无法预测的.即使是白色背景也可能变成黑色.

I regularly receive such files that I need to process and provide in several smaller formats. I do that with some PHP script using the GD library. The problem is that it is unpredictable whether those areas will turn out black or white in the processed versions. Even white backgrounds can turn into black.

所以我的问题是,是否可以某种方式检测到GD中的透明"区域并为其指定特定的颜色.

So my question is whether it is in some way possible to detect this "transparent" area in GD and assign it a specific color.

例如,查看这两个图像: http://www.bilbil.com/9156-thickbox_default/bus.jpg http://bilbil.com/img/p/9/1/5/6/9156.jpg

See for example those two images: http://www.bilbil.com/9156-thickbox_default/bus.jpg http://bilbil.com/img/p/9/1/5/6/9156.jpg

此刻,我使用以下代码:

At the moment I use this code:

$srcfile = "9158.jpg";
$dir ="/test/";
list($width, $height, $imgtype, $attr) = @getimagesize( $dir.$srcfile );
$src = imagecreatefromjpeg($dir.$srcfile);
$newheight=$newwidth = 800;
$img = imagecreatetruecolor ( $newwidth , $newheight );
$white = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $white);
imagecopyresampled($img, $src, ($newwidth-$width)/2, ($newheight-$height)/2, 0, 0, $width, $height, $width, $height);
if(!imagejpeg($img, $dir.'test.jpg', 97))
  echo("Error creating testimage");

推荐答案

在几乎所有情况下,您都可以使用左上角的像素颜色作为透明颜色.

In almost all the cases, you can use the top-left pixel color as the transparent color.

这篇关于PHP/GD:如何处理jpg透明度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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