当前位置:  开发笔记 > 编程语言 > 正文

使用PHP生成缩略图会导致图像质量不佳

如何解决《使用PHP生成缩略图会导致图像质量不佳》经验,为你挑选了2个好方法。

使用imagecreatetruecolor而不是imagecreate和imagecopyresampled而不是imagecopyresized.



1> tst..:

使用imagecreatetruecolor而不是imagecreate和imagecopyresampled而不是imagecopyresized.



2> philistyne..:

第三个参数值得包括Dominic指出.它指定了jpeg质量.

关于"看起来它已被压扁"的问题,记住,你是从源图像制作一个方形缩略图,它本身可能是也可能不是正方形.

解决此问题的一种方法是使用源尺寸来计算从源复制的全宽或全高(取决于图像是纵向还是横向)方形.这意味着用动态计算的东西替换imagecopyresized()的参数中的"0,0,0,0".

(编辑:示例)

function makeSquareThumb($srcImage, $destSize, $destImage = null) {
    //I'm sure there's a better way than this, but it works...
    //I don't like my folder and file checking in the middle, but need to illustrate the need for this. 

    $srcFolder = dirname($srcImage); //source folder
    $srcName = basename($srcImage); //original image filename

    //the IF ELSEIF ELSE below is NOT comprehensive - eg: what if the dest folder is the same as the source?
    //writeable nature of the destination is not checked!
    if(!destImage) {
        $destFolder = $srcFolder.'/thumbs/';
        if(!is_dir($destFolder)) {
            //make the thumbs folder if there isn't one!
            mkdir($destFolder);
        }
        $destImage = $destFolder.$srcName;
    } elseif (is_dir($destImage)) {
        $destFolder = $destImage;
        $destImage = $destFolder.'/'.$srcName;
    } else {
        $destFolder = dirname($destImage);
    }


    //Now make it!
    $srcCanvas = imagecreatefromjpeg($srcImage);
    $srcWidth = imagesx($srcCanvas);
    $srcHeight = imagesy($srcCanvas);

    //this let's us easily sample a square from the middle, regardless of apsect ratio.
    $shortSide = array($srcWidth,$srcHeight);
    sort($shortSide);

    $src_x = $srcWidth/2 - $shortSide[0]/2;
    $src_y = $srcHeight/2 - $shortSide[0]/2;

    //do it!
    $destCanvas = imagecreatetruecolor($destSize, $destSize);
    imagecopyresampled($destCanvas,$srcCanvas,0,0,$src_x,$src_y,$destSize,$destSize,$shortSide[0],$shortSide[0]);
    imagejpeg($destCanvas, $destImage);
}

推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有