PHP 图像调整大小 - 为什么图像上传但未调整大小?

发布于 2024-08-25 01:38:58 字数 3473 浏览 4 评论 0原文

背景
我有一个上传图像的脚本。一种用于保留原始图像,另一种用于调整图像大小。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋叶绚丽 2024-09-01 01:39:13

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)

当爱已成负担 2024-09-01 01:39:12

乍一看,我看不出脚本有什么问题,但如果没有一些测试输出和错误报告,这很难解决。

  1. 打开error_reporting(E_ALL)

  2. 查看$newname设置为什么

  3. 查看 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.

  1. Turn up error_reporting(E_ALL)

  2. See what $newname is set to

  3. See 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.

奈何桥上唱咆哮 2024-09-01 01:39:11

您是否检查过图像调整大小块实际上正在被使用?还要考虑其中的一些调试输出。我看不出任何明显错误

if ($width > $maxWidth || etc...) {
   echo "Hey, gotta shrink that there image";
   ... do the resizing ...
   $resizedImage = getimagesize($newname);
   var_dump($resizedImage); // see if the new image actually exists/what its stats are
   etc....
} else {
   echo "Woah, that's a small picture, I'll just make a straight copy instead";
}

您可能还想将 $newheight/$newwidth 四舍五入为整数值 - 在几乎所有情况下,您都会得到一些小数结果,并且图像没有小数像素。

顺便说一句,您的 ID 号生成器存在竞争条件:

$query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures");  
$row = mysql_fetch_array($query);  
$imagenumber = $row['number']+1; 

考虑两个上传几乎同时完成的情况。他们都会获得相同的 ID 号(例如 25)。然后,无论哪个上传的处理时间较长,都将“获胜”并覆盖速度较快的上传。

考虑重写数据库部分以使用事务,使用以下逻辑:

 1. start transaction
 2. insert skeleton record into the db and get its ID
 3. do image processing, copying, saving, etc...
 4. update record with the new image's stats
 5. commit the transaction

这样,事务将“隐藏”记录,因为它尚未提交,两个或多个同时上传无法获得相同的 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

if ($width > $maxWidth || etc...) {
   echo "Hey, gotta shrink that there image";
   ... do the resizing ...
   $resizedImage = getimagesize($newname);
   var_dump($resizedImage); // see if the new image actually exists/what its stats are
   etc....
} else {
   echo "Woah, that's a small picture, I'll just make a straight copy instead";
}

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:

$query = mysql_query("SELECT MAX(PicId) AS number FROM userpictures");  
$row = mysql_fetch_array($query);  
$imagenumber = $row['number']+1; 

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:

 1. start transaction
 2. insert skeleton record into the db and get its ID
 3. do image processing, copying, saving, etc...
 4. update record with the new image's stats
 5. commit the transaction

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文