降低imagepng的质量而不保存文件

时间:2018-03-25 08:39:02

标签: php image

我在images.php中使用此代码来显示图片:

imagepng($out);

如果我想降低缩略图的图像质量,我尝试了这段代码:

imagepng($out,$filename,$quality);

我想知道如何在不保存的情况下降低图像质量。

1 个答案:

答案 0 :(得分:1)

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;
        }
    }

    //Get file extension
    $exploding = explode(".",$file);
    $ext = end($exploding);

    switch($ext){
        case "png":
            $src = imagecreatefrompng($file);
        break;
        case "jpeg":
        case "jpg":
            $src = imagecreatefromjpeg($file);
        break;
        case "gif":
            $src = imagecreatefromgif($file);
        break;
        default:
            $src = imagecreatefromjpeg($file);
        break;
    }

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

    return $dst;
}

$filename = "/var/www/images/mynormalimage.png";
$resizedFilename = "/var/www/images/myresizedimage.png";

// resize the image with 300x300
$imgData = resize_image($filename, 300, 300);
// save the image on the given filename
imagepng($imgData, $resizedFilename);
// or according to the original format, use another method
// imagejpeg($imgData, $resizedFilename);
// imagegif($imgData, $resizedFilename);

https://ourcodeworld.com/articles/read/197/how-to-resize-an-image-and-reduce-quality-in-php-without-imagick enter code here