从图像创建缩略图

时间:2015-12-29 04:33:03

标签: php image thumbnails

我正在尝试从图片创建缩略图,但由于某种原因它无法正常工作。我做错了什么?

<?php

function make_thumb($src, $dest, $desired_width) {

/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);

/* find the "desired height" of this thumbnail, relative to the desired width  */
$desired_height = floor($height * ($desired_width / $width));

/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);

/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);

} //end of function make_thumb($src, $dest, $desired_width)

make_thumb("uploads/643Full-HD-Space-Wallpapers-Widescreen.jpg", "test", 100);

?>

1 个答案:

答案 0 :(得分:2)

你的功能对我有用,但是,我必须给目的地一个jpeg扩展名,因为它是一个有效的jpeg图像:

//---------------------------------------------------------------------vvv
make_thumb("uploads/643Full-HD-Space-Wallpapers-Widescreen.jpg", "test.jpg", 100);

修改

根据您的评论,这将是完整的功能:

function make_thumb($src, $dest, $desired_width)
    {
        // Make directory if not made
        if(!is_dir($dest))
            mkdir($dest,0755,true);
        // Get path info
        $pInfo  =   pathinfo($src);
        // Save the new path using the current file name
        $dest   =   $dest."/".$pInfo['basename'];
        // Do the rest of your stuff and things...
        $source_image = imagecreatefromjpeg($src);
        $width = imagesx($source_image);
        $height = imagesy($source_image);
        $desired_height = floor($height * ($desired_width / $width));
        $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
        imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
        imagejpeg($virtual_image, $dest);
    }

// Create file here
make_thumb("http://res.cloudinary.com/demo/image/upload/w_250,q_90/happy_dog.jpg", "test", 100);