首页 > 解决方案 > 在 PHP 中调整和保存 jpg、png 和 gif

问题描述

我在这里找到了 Ian Atkin 的解决方案 - Resize image in PHP - 并尝试对其进行修改以适应 png 和 gif,并保存调整大小的图像。Jpg 有效,但我得到了 png 和 gif 的黑色图像(大小正确)。我不知道我在做什么错。这是代码:

function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
    if ($width > $height) {
        $width = ceil($width-($width*abs($r-$w/$h)));
    } else {
        $height = ceil($height-($height*abs($r-$w/$h)));
    }
    $newwidth = $w;
    $newheight = $h;
} else {
    if ($w/$h > $r) {
        $newwidth = $h*$r;
        $newheight = $h;
    } else {
        $newheight = $w/$r;
        $newwidth = $w;
    }
}

if($extension=="gif") {
    $src = imagecreatefromgif($file);
} elseif($extension=="png") {
    $src = imagecreatefrompng($file);
} else {
    $src = imagecreatefromjpeg($file);
}

$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

if($extension=="gif") {
    imagegif($dst, $file);
} elseif($extension=="png") {
    imagepng($dst, $file);
} else {
    imagejpeg($dst, $file);
}
return $dst;

}

非常感谢!

标签: phppngjpeggifimage-resizing

解决方案


推荐阅读