上传图片,创建其缩略图并保存。

3

假设我上传了一张图片。我可以获取其临时目录,然后使用move_uploaded_file()将其保存,但是如果我想创建一个缩略图并将两者都保存在某个文件夹中怎么办?

我知道如何保存上传的图片,但不知道如何开始操作图片并在创建缩略图后保存它。


1
您不需要在标题中加入“[PHP]”,这就是标签的作用。 - Wrikken
4个回答

3

1

你需要安装php gd或者imagemagick。以下是一个使用gd进行调整大小的快速示例(来自手册):

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb, 'thumbs/thumb1.jpg');
?>

我该如何将图像保存在某个文件夹中而不是显示它? - Rodrigo Souza
imagejpeg函数的第二个参数是文件名。我已经更新了示例。另外,请查看手册页面:http://php.net/manual/en/function.imagejpeg.php - Sergey Eremin

1
我总是使用Verot PHP上传类,并且一直都很成功。这个PHP类非常简单易用,可以按您想要的任何方式操作图像。它还可以将图像保存在指定的文件夹中。
您可以从此处下载它。
要查看上传类的演示和易于理解的文档,请访问http://www.verot.net/php_class_upload_samples.htm?PHPSESSID=5375147e959625e56e0127f3458a6385
以下是我从网站上获取的一个简单示例。
//How to use it?
//Create a simple HTML file, with a form such as:

 <form enctype="multipart/form-data" method="post" action="upload.php">
   <input type="file" size="32" name="image_field" value="">
   <input type="submit" name="Submit" value="upload">
 </form>

//Create a file called upload.php:

  $handle = new upload($_FILES['image_field']);
  if ($handle->uploaded) {
      $handle->file_new_name_body   = 'image_resized';
      $handle->image_resize         = true;
      $handle->image_x              = 100;
      $handle->image_ratio_y        = true;
      $handle->process('/home/user/files/');
      if ($handle->processed) {
          echo 'image resized';
          $handle->clean();
      } else {
          echo 'error : ' . $handle->error;
      }
  }

//How to process local files?
//Use the class as following, the rest being the same as above:

  $handle = new upload('/home/user/myfile.jpg');

0

使用ImageMagick。 在Stack Overflow上查看之前的帖子 使用PHP生成ImageMagick缩略图-使用-crop参数 PHP:创建裁剪后的图像缩略图,出现问题 PHP中的图像处理类 http://www.imagemagick.org/

define('THUMB_WIDTH', 60);
define('THUMB_HEIGHT', 80);
define('MAGICK_PATH','/usr/local/bin/');

function makeThumbnail($in, $out) {
    $width = THUMB_WIDTH;
    $height = THUMB_HEIGHT;
    list($w,$h) = getimagesize($in);

    $thumbRatio = $width/$height;
    $inRatio = $w/$h;
    $isLandscape = $inRatio > $thumbRatio;

    $size = ($isLandscape ? '1000x'.$height : $width.'x1000');
    $xoff = ($isLandscape ? floor((($inRatio*$height)-$width)/2) : 0);
    $command = MAGICK_PATH."convert $in -resize $size -crop {$width}x{$height}+{$xoff}+0 ".
        "-colorspace RGB -strip -quality 90 $out";

    exec($command);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接