假设我上传了一张图片。我可以获取其临时目录,然后使用move_uploaded_file()
将其保存,但是如果我想创建一个缩略图并将两者都保存在某个文件夹中怎么办?
我知道如何保存上传的图片,但不知道如何开始操作图片并在创建缩略图后保存它。
假设我上传了一张图片。我可以获取其临时目录,然后使用move_uploaded_file()
将其保存,但是如果我想创建一个缩略图并将两者都保存在某个文件夹中怎么办?
我知道如何保存上传的图片,但不知道如何开始操作图片并在创建缩略图后保存它。
你需要安装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');
?>
//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');
使用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);
}