PHP上传不同缩略图大小的图片

时间:2015-02-28 03:57:19

标签: php image

我已经在网上搜索了这么长时间,但我已经看到有上传的图像能够执行任务,但我想知道,如果有一种方法可以上传图像然后自动转换上传的图像在不同的缩略图大小,如50x50,150x150,250x250。

先谢谢。

2 个答案:

答案 0 :(得分:1)

不确定。

如果您的服务器上安装了GD,则可以使用http://php.net/manual/en/book.image.php

如果您有imagemagick,可以使用http://php.net/manual/en/book.imagick.php

以下是使用GD的快速示例。这假设您使用<input type="file" name="FileUploadName">元素上传图片。

$uploadedFilePath = $_FILES["FileUploadName"]["tmp_name"];
$somePermanentPath = "/tmp/mynewfile";
move_uploaded_file($uploadedFilePath, $somePermanentPath);
$srcImg = imagecreatefromstring(file_get_contents($somePermanentPath));
$srcW   = imagesx($srcImg);
$srcH   = imagesy($srcImg);
if ($srcW > $srcH)
{
    $widthFactor  = 1;
    $heightFactor = $srcH / $srcW;
}
else
{
    $heightFactor = 1;
    $widthFactor  = $srcW / $srcH;
}
$width50   = 50 * $widthFactor;
$height50  = 50 * $heightFactor;
$width150   = 150 * $widthFactor;
$height150  = 150 * $heightFactor;

$thumb50 = imagecreatetruecolor(50, 50);    
$thumb150 = imagecreatetruecolor(150, 150);    

imagecopyresampled($thumb50, $srcImg, 0, 0, 0, 0, 50, 50, $srcW, $srcH); //the 0's can be changed to deal with centering
imagecopyresampled($thumb150, $srcImg, 0, 0, 0, 0, 50, 50, $srcW, $srcH); //the 0's can be changed to deal with centering


//save as png
imagepng($thumb50, "/tmp/somefinallocation50.png");
imagepng($thumb150, "/tmp/somefinallocation150.png");

注意:如果你想处理那些东西,你必须添加额外的逻辑来居中和创建背景空白。

确认:此示例取自ActiveWAFLDblEj\Multimedia\Image::ResampleAndSave()方法,删除了一些代码以方便使用。

答案 1 :(得分:0)

这是一个可用于在安装了imagick后调整图像大小的功能。无论是gif还是jpeg。

 function resize($srcfile, $newWidth, $newHeight, $newfile){
        list($srcW, $srcH) = getimagesize($srcfile);
        $newWH = $srcWH = $srcW / $srcH;
        if($newHeight) $newWH = $newWidth / $newHeight;
        if($srcW > $newWidth || ($newHeight && $srcH > $newHeight)){
            if($newWH <= $srcWH){
                $ftoW = $newWidth;
                $ftoH = $ftoW * ($srcH / $srcW);
            }else{
                $ftoH = $newHeight;
                $ftoW = $ftoH * ($srcW / $srcH);
            }
            $thumb = new Imagick($srcfile);
            $thumb->resizeImage($ftoW, $ftoH, substr($srcfile, -3) == 'gif' ? Imagick::FILTER_CUBIC : imagick::FILTER_UNDEFINED, 1);
            $thumb->setCompression(Imagick::COMPRESSION_JPEG);
            $thumb->setCompressionQuality(50);
            $thumb->writeImage($newfile);
            $thumb->destroy();
            Return array($ftoW, $ftoH);
        }else{
            $thumb = new Imagick($srcfile);
            if(substr($srcfile, -3) == 'gif') $thumb->resizeImage($srcW, $srcH, Imagick::FILTER_CUBIC, 1);
            //$thumb->setCompression(Imagick::COMPRESSION_JPEG);
            //$thumb->setCompressionQuality(50);
            $thumb->writeImage($newfile);
            $thumb->destroy();
            Return array($srcW, $srcH);
        }
    }