0
$sourcePath = 'images/'; // Path of original image
$sourceUrl = '';
$sourceName = 'photo1.jpg'; // Name of original image
$thumbPath = 'thumbs/'; // Writeable thumb path
$thumbUrl = 'thumbs/';
$thumbName = "test_thumb.jpg"; // Tip: Name dynamically
$thumbWidth = 100; // Intended dimension of thumb

// Beyond this point is simply code.
$sourceImage = imagecreatefromjpeg("$sourcePath/$sourceName");
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);

$targetImage = imagecreate($thumbWidth,$thumbWidth);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
imagejpeg($targetImage, "$thumbPath/$thumbName");

// By now, the thumbnail is copied into the $thumbpath
// as the file name specified in $thumbName, so display
echo "<img src='$thumbUrl$thumbName' alt=''>";

上面的代码给了我一个缩略图,这很棒,但是图像质量很糟糕。看起来图像的颜色反转了,看起来像是被压扁了。做这个我整天头疼。有人有想法么?

4

3 回答 3

18

使用imagecreatetruecolor代替 imagecreate 和imagecopyresampled代替 imagecopyresized。

于 2008-11-18T12:07:27.793 回答
7

正如 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);
}
于 2008-11-18T12:12:59.547 回答
1

尝试:

imagejpeg($targetImage, "$thumbPath/$thumbName", 100);
于 2008-11-18T12:03:32.920 回答