PHP 图像调整大小 - 为什么图像上传但未调整大小?
背景
我有一个上传图像的脚本。一种用于保留原始图像,另一种用于调整图像大小。 1. 如果图像尺寸(宽度和高度)在最大尺寸内,我会使用简单的“复制”直接到文件夹 UserPics。 2.如果原始尺寸大于最大尺寸,我想将宽度和高度调整到最大尺寸之内。 两者都将图像上传到文件夹,但在情况 2 中,图像不会调整大小。
问题
脚本有问题吗?
是不是设置有问题?
设置
服务器:WAMP 2.0
PHP:5.3.0
PHP.ini:启用GD2,内存=128M(已尝试1000M)
尝试上传的图像类型:jpg、jpeg、gif 和 png(所有这些的结果相同)
SCRIPT
if (isset($_POST['adduserpic'])) {
// Check errors on file
if ($_FILES["file"]["error"] > 0) {
echo $_FILES["file"]["error"]." errors<br>";
} else {
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES["file"]["tmp_name"];
//Uploaded image
$filename = stripslashes($_FILES['file']['name']);
//Read filetype
$i = strrpos($filename,".");
if (!$i) { return ""; }
$l = strlen($filename) - $i;
$extension = substr($filename,$i+1,$l);
$extension = strtolower($extension);
//New picture name = maxid+1 (from database)
$query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures");
$row = mysql_fetch_array($query);
$imagenumber = $row['number']+1;
//New name of image (including path)
$image_name=$imagenumber.'.'.$extension;
$newname = "UserPics/".$image_name;
//Check width and height of uploaded image
list($width,$height)=getimagesize($uploadedfile);
//Check memory to hold this image (added only as checkup)
$imageInfo = getimagesize($uploadedfile);
$requiredMemoryMB = ( $imageInfo[0] * $imageInfo[1] * ($imageInfo['bits'] / 8) * $imageInfo['channels'] * 2.5 ) / 1024;
echo $requiredMemoryMB."<br>";
//Max dimensions that can be uploaded
$maxwidth = 20;
$maxheight = 20;
// Check if dimensions shall be original
if ($width > $maxwidth || $height > $maxheight) {
//Make jpeg from uploaded image
if ($extension=="jpg" || $extension=="jpeg" || $extension=="pjpeg" ) {
$modifiedimage = imagecreatefromjpeg($uploadedfile);
} elseif ($extension=="png") {
$modifiedimage = imagecreatefrompng($uploadedfile);
} elseif ($extension=="gif") {
$modifiedimage = imagecreatefromgif($uploadedfile);
}
//Change dimensions
if ($width > $height) {
$newwidth = $maxwidth;
$newheight = ($height/$width)*$newwidth;
} else {
$newheight = $maxheight;
$newwidth = ($width/$height)*$newheight;
}
//Create new image with new dimensions
$newdim = imagecreatetruecolor($newwidth,$newheight);
imagecopyresized($newdim,$modifiedimage,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($modifiedimage,$newname,60);
// Remove temp images
imagedestroy($modifiedimage);
imagedestroy($newdim);
} else {
// Just add picture to folder without resize (if org dim < max dim)
$newwidth = $width;
$newheight = $height;
$copied = copy($_FILES['file']['tmp_name'], $newname);
}
//Add image information to the MySQL database
mysql_query("SET character_set_connection=utf8", $dbh);
mysql_query("INSERT INTO userpictures (PicId, Picext, UserId, Width, Height, Size) VALUES('$imagenumber', '$extension', '$_SESSION[userid]', '$newwidth', '$newheight', $size)")
BACKGROUND
I have a script to upload an image. One to keep the original image and one to resize the image.
1. If the image dimensions (width & height) are within max dimensions I use a simple "copy" direct to folder UserPics.
2. If the original dimensions are bigger than max dimensions I want to resize the width and height to be within max.
Both of them are uploading the image to the folder, but in case 2, the image will not be resized.
QUESTION
Is there something wrong with the script?
Is there something wrong with the settings?
SETTINGS
Server: WAMP 2.0
PHP: 5.3.0
PHP.ini: GD2 enabled, Memory=128M (have tried 1000M)
Tried imagetypes uploaded: jpg, jpeg, gif, and png (same result for all of them)
SCRIPT
if (isset($_POST['adduserpic'])) {
// Check errors on file
if ($_FILES["file"]["error"] > 0) {
echo $_FILES["file"]["error"]." errors<br>";
} else {
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES["file"]["tmp_name"];
//Uploaded image
$filename = stripslashes($_FILES['file']['name']);
//Read filetype
$i = strrpos($filename,".");
if (!$i) { return ""; }
$l = strlen($filename) - $i;
$extension = substr($filename,$i+1,$l);
$extension = strtolower($extension);
//New picture name = maxid+1 (from database)
$query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures");
$row = mysql_fetch_array($query);
$imagenumber = $row['number']+1;
//New name of image (including path)
$image_name=$imagenumber.'.'.$extension;
$newname = "UserPics/".$image_name;
//Check width and height of uploaded image
list($width,$height)=getimagesize($uploadedfile);
//Check memory to hold this image (added only as checkup)
$imageInfo = getimagesize($uploadedfile);
$requiredMemoryMB = ( $imageInfo[0] * $imageInfo[1] * ($imageInfo['bits'] / 8) * $imageInfo['channels'] * 2.5 ) / 1024;
echo $requiredMemoryMB."<br>";
//Max dimensions that can be uploaded
$maxwidth = 20;
$maxheight = 20;
// Check if dimensions shall be original
if ($width > $maxwidth || $height > $maxheight) {
//Make jpeg from uploaded image
if ($extension=="jpg" || $extension=="jpeg" || $extension=="pjpeg" ) {
$modifiedimage = imagecreatefromjpeg($uploadedfile);
} elseif ($extension=="png") {
$modifiedimage = imagecreatefrompng($uploadedfile);
} elseif ($extension=="gif") {
$modifiedimage = imagecreatefromgif($uploadedfile);
}
//Change dimensions
if ($width > $height) {
$newwidth = $maxwidth;
$newheight = ($height/$width)*$newwidth;
} else {
$newheight = $maxheight;
$newwidth = ($width/$height)*$newheight;
}
//Create new image with new dimensions
$newdim = imagecreatetruecolor($newwidth,$newheight);
imagecopyresized($newdim,$modifiedimage,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($modifiedimage,$newname,60);
// Remove temp images
imagedestroy($modifiedimage);
imagedestroy($newdim);
} else {
// Just add picture to folder without resize (if org dim < max dim)
$newwidth = $width;
$newheight = $height;
$copied = copy($_FILES['file']['tmp_name'], $newname);
}
//Add image information to the MySQL database
mysql_query("SET character_set_connection=utf8", $dbh);
mysql_query("INSERT INTO userpictures (PicId, Picext, UserId, Width, Height, Size) VALUES('$imagenumber', '$extension', '$_SESSION[userid]', '$newwidth', '$newheight', $size)")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1)检查权限。确保您的 UserPics 目录可以由运行 Web 进程的用户写入(例如,debian 系统上的 www-data)。我不熟悉 Windows 上此类事情的系统权限,但如果我自己编写此内容,我会检查这一点(我已经,而且我可能已经这样做了)。
2)本身不相关,但请查看 http://sourceforge.net/projects/littleutils/
我在所有上传的图像上运行 opt-gif 和 opt-jpg 以无损地节省磁盘空间(我的应用程序不需要丢失的内容)
1) Check permissions. make sure your UserPics directory can be written by the user running the web process (e.g., www-data on a debian system). I'm not familiar with system permissions on windows for this kind of thing, but that's what I would check if I were writing this myself (and I have, and I probably did).
2) Not related, per se, but check out http://sourceforge.net/projects/littleutils/
I run opt-gif and opt-jpg on all my uploaded images to save disk space, losslessly (my app doesn't need what's lost)
乍一看,我看不出脚本有什么问题,但如果没有一些测试输出和错误报告,这很难解决。
打开
error_reporting(E_ALL)
查看
$newname
设置为什么查看 copy() 命令的作用
我敢打赌,当您转动时,您会得到一些东西错误报告。
顺便说一句,要找出文件的扩展名,我将使用
pathinfo
。I can't see anything wrong with the script at first glance but this is awfully hard to solve without some test output and error reporting.
Turn up
error_reporting(E_ALL)
See what
$newname
is set toSee what the copy() command does
I bet you are getting something when you turn error reporting on.
To find out the file's extension, by the way, I would use
pathinfo
.您是否检查过图像调整大小块实际上正在被使用?还要考虑其中的一些调试输出。我看不出任何明显错误
您可能还想将 $newheight/$newwidth 四舍五入为整数值 - 在几乎所有情况下,您都会得到一些小数结果,并且图像没有小数像素。
顺便说一句,您的 ID 号生成器存在竞争条件:
考虑两个上传几乎同时完成的情况。他们都会获得相同的 ID 号(例如 25)。然后,无论哪个上传的处理时间较长,都将“获胜”并覆盖速度较快的上传。
考虑重写数据库部分以使用事务,使用以下逻辑:
这样,事务将“隐藏”记录,因为它尚未提交,两个或多个同时上传无法获得相同的 ID 号,并且如果在图像处理过程中出现任何故障(内存不足、磁盘空间不足、源图像损坏等),您只需回滚事务并清理混乱即可。
我
Have you checked that the image resizing block is actually being used? Consider some debug output in there as well. I can't see anything obviously wrong
You might also want to round off the $newheight/$newwidth to integer values - In almost all cases, you'll get some fractional result and images don't have fractional pixels.
As an aside, you've got a race condition with your ID number generator:
Consider the case of two uploads completing at almost the same time. They'll both get the same ID number (say, 25). And then whichever of the uploads takes longer to process will "win" and overwrite the faster one.
Consider rewriting the database portion to use a transaction, using the following logic:
This way, the transaction will "hide" the record as it's not committed yet, there's no way for two or more simultaneous uploads to get the same ID number, and if anything fails during image processing (insufficient ram, disk space, corrupt source image, etc...) you just roll back the transaction and clean up the mess.
I