【发布时间】:2011-09-28 06:45:43
【问题描述】:
我目前正在为一个 PHP 脚本(不是我写的)编写前端,它可以调整图像(PNG、GIF、JPG)的大小并将它们保存为 JPEG。它非常简单,在输入 JPEG 时效果很好,但似乎不适用于 PNG 或 GIF 图像。
这是调整大小的代码:
<?php
header ("Content-type: image/jpeg");
$img = $_GET['img'];
header("Content-Disposition: attachment; filename=resized-$img");
$percent = $_GET['percent'];
$constrain = $_GET['constrain'];
$w = $_GET['w'];
$h = $_GET['h'];
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
// autocompute width if only height is set
$w = (100 / ($sh / $h)) * .01;
$w = @round ($sw * $w);
} elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
// get the smaller resulting image dimension if both height
// and width are set and $constrain is also set
$hx = (100 / ($sw / $w)) * .01;
$hx = @round ($sh * $hx);
$wx = (100 / ($sh / $h)) * .01;
$wx = @round ($sw * $wx);
if ($hx < $h) {
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
} else {
$w = (100 / ($sh / $h)) * .01;
$w = @round ($sw * $w);
}
}
}
$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile ($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
// Output resized image
@ImageJPEG ($thumb);
}
?>
您能看出 png/gif 选项不起作用的任何原因吗? 我有最新的 GD 并启用了所有格式,并且正在运行 php 5.3.3
提前致谢。
【问题讨论】:
-
当您尝试使用其中一种格式时会发生什么?尝试删除前面的 @ 符号,让我们知道您遇到了什么错误。
-
在 chrome 中我得到网页不可用'错误 101 (net::ERR_CONNECTION_RESET):连接已重置。' Firefox 说“连接已重置”删除“@”无效
-
我用 "?w=20&h=20&img=1.png" 对其进行了测试,它适用于 PNG 文件。你的查询字符串是什么?
-
您是否尝试过清除缓存?我读到一些防病毒软件也会导致这种情况。否则,您的代码可能存在导致连接重置的问题。我不是
imagecreatefromjpeg() or imagecreatefromgif() or ...的最大粉丝。你应该在下面看到我的答案。它可能无法解决您的问题,但会更优雅。
标签: php image resize png imagecreatefrompng