上传图片,创建拇指然后保存

时间:2010-07-19 20:46:45

标签: php image image-manipulation thumbnails

假设我上传了一张图片。我可以获取它的临时目录,然后用move_uploaded_file()保存它,但是如果我还想创建一个拇指并将它们保存在某个文件夹中呢?

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

4 个答案:

答案 0 :(得分:3)

GD库使这非常容易。

您需要计算原始图像的尺寸,以便保留纵横比,然后只是以较小的尺寸重新采样图像。这是一个很好的教程,清楚地解释了所有内容:http://www.phptoys.com/e107_plugins/content/content.php?content.46

答案 1 :(得分:1)

您需要php gdimagemagick。这是一个使用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');
?>

答案 2 :(得分:1)

我总是使用Verot PHP Upload类,并且总是使用它。这个PHP类实现起来非常简单,可以按照您想要的任何方式操作图像。它也可以将图像保存在指定的文件夹中。

您可以从here

下载

要查看上传课程的演示和简单文档,请访问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');

答案 3 :(得分:0)

使用Image magick。 检查堆栈溢出的先前帖子 Imagemagick thumbnail generation with php - using -crop PHP: Creating cropped thumbnails of images, problems Image processing class in 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);
}