PHP图像调整大小不适用于png / gif

时间:2011-07-04 16:44:32

标签: php image resize png imagecreatefrompng

我正在编写一个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

提前致谢。

3 个答案:

答案 0 :(得分:3)

$xgetimagesize()数组的第三项包含图像的mime类型。您应该使用它而不是使用or语句并尝试所有类型。

switch ( $x[2] ) 
{
  case 1: $im = imagecreatefromgif($img); break;
  case 2: $im = imagecreatefromjpeg($img); break;
  case 3: $im = imagecreatefrompng($img); break;
  default: trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
}

答案 1 :(得分:0)

尝试imagecreatefromstring(file_get_contents($img))而不是你那个可怕的构造。或者做一个正确的switch语句并明确确定使用哪一个而不是依次尝试每个语句。

答案 2 :(得分:0)

除了Francois Deschenes已经说过的内容之外......请删除所有@并转发错误报告(error_reporting(E_ALL);)。你压抑了很多可能的错误来源,你自己调试这个脚本几乎是不可能的。尝试编写甚至在任何地方都不使用单个@的脚本......