在PHP中调整和保存jpg,png和gif的大小

时间:2020-09-12 12:30:31

标签: php png jpeg gif image-resizing

我在这里找到了伊恩·阿特金(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;

}

非常感谢您!

0 个答案:

没有答案
相关问题