【发布时间】:2014-05-07 03:45:15
【问题描述】:
这是我用来显示或调整大小并显示缓存标头的部分代码。它适用于 JPG 图像。但是 PNG 图像被添加为黑色背景。此类问题可在 SO 和 Google 中找到,但接受或建议的解决方案几乎是相同的:imagealphablending - FALSE 和 imagesavealpha - TRUE。但就我而言,没有任何效果。会有什么问题?
$image_information=getimagesize($img);
if($image_information['mime']=='image/gif')
{
$img=imagecreatefromgif($img);
$type="gif";
$image_header="image/gif";
}
elseif($image_information['mime']=='image/png')
{
$img=imagecreatefrompng($img);
$type="png";
$image_header="image/png";
}
else
{
$img=imagecreatefromjpeg($img);
$type="jpg";
$image_header="image/jpeg";
}
$width=imagesx($img);
$height=imagesy($img);
if((isset($w))&(!isset($h))) // If Width or Height is posted, calculate the aspect dimensions
{
$h=($height/$width*$w);
}
if((isset($h))&(!isset($w)))
{
$w=(($h*$width)/$height);
}
if(!isset($w))
{
$w=$width;
}
if(!isset($h))
{
$h=$height;
}
$new_image=imagecreatetruecolor($w, $h);
if($type=="gif")
{
$background=imagecolorallocate($new_image, 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($new_image, $background);
}
elseif($type=="png")
{
imagealphablending($new_image, FALSE);
imagesavealpha($new_image, TRUE);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefilledrectangle($new_image, 0, 0, $w, $h, $transparent);
}
imagecopyresampled($new_image,$img,0,0,0,0,$w,$h,$width,$height);
$seconds_to_cache = 864000; // Add cache headers
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control:max-age=$seconds_to_cache, must-revalidate");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
header('Content-Type: $image_header');
if($type="jpg")
imagejpeg($new_image, NULL, 75);
elseif($type=="png")
imagepng($new_image, NULL, 75);
elseif($type=="gif")
imagegif($new_image, NULL);
imagedestroy($new_image);
编辑:我将图像保存到我的系统,尝试打开,
- Picasa 照片查看器 - 图片以黑色背景打开。
- Ms Paint - 图像以黑色背景打开。
- Photoshop CS6 - 弹出错误消息:由于程序错误而无法打开。
【问题讨论】:
-
澄清一下,问题是通过PHP保存图像还是通过PHP在网页上显示图像?
-
用 PHP 显示图像。当需要多种尺寸时,我使用以下限制,“images/image-name.extension/int/int”-> 扩展名将是 jpg 或 png 或 gif,第一个 int 将是数字宽度,第二个将是数字高度.可以省略 Wither 或两个 int 值。
-
@Timvp:很好,正在使用中。