2017-02-10 82 views
1

我正在构建一个评论网站,并遇到了有关我的图像上传处理的问题。我已经设置了我的php.ini,允许max_file_uploadsize为10M,post_max_size为60M,但我将文件上传大小限制为6MB。我正在使用smart_resize_image function来调整图像大小。我允许上传最多5个图像,并使用foreach循环遍历$ _FILES数组。这里是我的图像处理代码:文件上传循环内存耗尽

 $allowed = array('image/pjpeg', 'image/jpeg', 'image/jpg', 'image/JPG', 'image/PNG', 'image/png'); 
     $i = 1; 
     foreach($_FILES as $image) { 
      if (file_exists($image['tmp_name'])) { 
       if (in_array($image['type'], $allowed)) { 
        if($image['size'] < 6291456) { 
         include_once('/inc/smart_resize_image.function.php'); 
         $movedL = '/public_html/ureview/images/restaurants/'.$pid.'/'.$sid.'-'.$i.'.jpg'; 
         smart_resize_image($image['tmp_name'], null, 800, 500, true,$movedL, true,false,100); 
         $i++; 
        }else{ 
         echo'Image #'.$i.' file size limit of 5MB!'; 
         exit(); 
        } 
       }else{ 
        echo'Image #'.$i.' file type not allowed!'; 
        exit(); 
       } 
      } 
     }  

我得到的错误是:

Allowed memory size of 33554432 bytes exhausted (tried to allocate 12288 bytes) in /inc/smart_resize_image.function.php 

我认为这个问题是什么,该smart_resize_image函数处理后断开链接但没有释放内存。我知道有多个网站处理图片上传,所以这是可能的,但我无法弄清楚我需要在代码中进行更改。

编辑: 我正在查看是否有在我的代码中会导致错误发生的低效率。

+1

的[允许的可能的复制内存大小33554432字节用尽(试图分配43148176字节)在PHP](http://stackoverflow.com/questions/415801/allowed-memory-size-of-33554432-bytes-exhausted-tried-to-allocate-43148176 -byte) –

+0

我不会将memory_limit设置为-1,正如上面的问题所暗示的。我的问题是询问在我的代码中是否存在效率低下会导致错误发生 –

+0

那么,您可以阅读[imagedestroy](http://php.net/manual/en/function.imagedestroy.php)并尝试在你的代码中实现它 –

回答

1

我看到的smart_resize_image$output参数描述为

@param $输出 - 新文件的名称(如果需要包括路径)

但我也看到line 110你可以通过'return',它会使该函数返回图像资源:

$res = smart_resize_image($image['tmp_name'], null, 800, 500, true,'return', true,false,100); 

现在你有了可以销毁的办法,但是在销毁之前,你需要将它保存为文件(smart_resize_image()函数的第218-226行,你现在需要实现)。因此,这是你怎么做:

// smart_resize_image($image['tmp_name'], null, 800, 500, true,$movedL, true,false,100); /* OLD */ 

$quality = 100; 
$info = getimagesize($image['tmp_name']); 

$res = smart_resize_image($image['tmp_name'], null, 800, 500, true,'return', true,false,100); 

switch ($info[2]) { 
    case IMAGETYPE_GIF: imagegif($res, $movedL); break; 
    case IMAGETYPE_JPEG: imagejpeg($res, $movedL, $quality); break; 
    case IMAGETYPE_PNG: 
    $quality = 9 - (int)((0.9*$quality)/10.0); 
    imagepng($res, $movedL, $quality); 
    break; 
    default: break; 
} 
imagedestroy ($res); // Now you should be able to destroy the resource (returned from the 'smart_resize_image' function) 

上面的代码现在使用的释放与图像资源相关联的任何记忆,并希望该imagedestroy()会阻止你得到的内存耗尽错误

+0

我唯一需要改变的是在smart_resize_image函数中返回后的第一个“true”必须设置为false,因此该函数并未取消链接原始图像。 –

+0

@ActionCoding谢谢你让我知道。在调用'smart_resize_image'函数之前,我切换了顺序并调用了'$ info = getimagesize($ image ['tmp_name']);'所以现在你不需要自己解除链接 –