【发布时间】:2011-01-10 17:18:03
【问题描述】:
我正在编写一个使用 PHP 上传图片的脚本,我想让它在保存之前将图片的大小调整为 180。
我尝试使用 WideImage 库和 ->saveFileTO(...) 但是当我在页面中包含 WideImage.php 时,页面变为空白!!
所以这是我的脚本,如果你能帮助我并告诉我如何让它保存调整大小的版本
【问题讨论】:
标签: php file-upload autoresize
我正在编写一个使用 PHP 上传图片的脚本,我想让它在保存之前将图片的大小调整为 180。
我尝试使用 WideImage 库和 ->saveFileTO(...) 但是当我在页面中包含 WideImage.php 时,页面变为空白!!
所以这是我的脚本,如果你能帮助我并告诉我如何让它保存调整大小的版本
【问题讨论】:
标签: php file-upload autoresize
您可以使用PHP GD library 在上传时调整图像大小。
以下代码应该让您了解如何实现调整大小:
// Get the image info from the photo
$image_info = getimagesize($photo);
$width = $new_width = $image_info[0];
$height = $new_height = $image_info[1];
$type = $image_info[2];
// Load the image
switch ($type)
{
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($photo);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($photo);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($photo);
break;
default:
die('Error loading '.$photo.' - File type '.$type.' not supported');
}
// Create a new, resized image
$new_width = 180;
$new_height = $height / ($width / $new_width);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the new image over the top of the original photo
switch ($type)
{
case IMAGETYPE_JPEG:
imagejpeg($new_image, $photo, 100);
break;
case IMAGETYPE_GIF:
imagegif($new_image, $photo);
break;
case IMAGETYPE_PNG:
imagepng($new_image, $photo);
break;
default:
die('Error saving image: '.$photo);
}
【讨论】:
您可以使用我为此类任务编写的类:
http://code.google.com/p/image2/source/browse/#svn/trunk/includes/classes
<?php
try
{
$image = new Image2($path_to_image);
}
catch (NotAnImageException $e)
{
printf("FILE PROVIDED IS NOT AN IMAGE, FILE PATH: %s", $path_to_image);
}
$image -> resize(array("width" => 180)) -> saveToFile($new_path); // be sure to exclude the extension
$new_file_location = $image -> getFileLocation(); // this will include the extension for future use
【讨论】:
您甚至不需要使用 WideImage 库。
在此处检查此脚本: http://bgallz.org/502/php-upload-resize-image/
您首先上传图像并保存到临时图像文件。该脚本运行一个带有最大高度或最大宽度输入的表单。因此它将根据新的宽度/高度生成一个新的图像文件,然后将临时图像复制到服务器上创建的新图像上。
您可以通过以下代码看到这一点:
// Create temporary image file.
$tmp = imagecreatetruecolor($newwidth,$newheight);
// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
【讨论】:
不要使用任何库 检查这个脚本 http://dr-wordpress.blogspot.com/2013/12/image-resizing-using-php.html 刚刚给出了(0-99)的图像质量 此代码将在上传时自动调整图像大小
【讨论】: