在php中调整多个图像的大小而不超出内存限制
我目前正在尝试获取一个表单,该表单允许使用 PHP 在服务器上上传多个图像并调整其大小。客户端上传的每张图片大小约为 2.5mb。
我目前正在使用 move_uploaded_file()
函数。
将文件移动到服务器上没有问题。当我尝试裁剪时,问题就出现了。我的主机上没有 ImageMagick ,我正在使用此设置(并非所有代码都是相关的,这是与 $width
等循环中的),针对不同的裁剪尺寸进行更改)
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, $output_filename, 80);
就目前情况而言,这只适用于 2 个图像。如果提交了 3 个或更多,我会收到“内存耗尽”错误。我对此进行了研究,因为我的内存限制是 120mb。显然,imagecreatefromjpeg
函数使用了大量内存,特别是如果文件具有较大的分辨率(我的就是这样 - 因此为什么我需要它们裁剪/调整大小)。
有谁知道更有效的方法来完成这项任务?我在谷歌上进行了研究,但每个人都使用与我相同的技术。
I am currently trying to get a form which will allow multiple images to be uploaded and resized on the server using PHP. Each uploaded image by the client is around 2.5mb in size.
I am currently using the move_uploaded_file()
function.
There are no issues to move the files onto the server. The problem arises when I try to crop. Having not ImageMagick on my host I am using this setup (not all the code just what's relevant, this is in a loop with $width
etc. changing for the different crop sizes)
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
imagejpeg($image_p, $output_filename, 80);
As it stands this will only work for 2 images. If there is 3 or more submitted I get a 'memory exhausted' error. I have researched into this as my memory limit is 120mb. Apparently the imagecreatefromjpeg
function uses a lot of memory, especially if the file has a large resolution (which mine does - hence why I need them cropped/resized).
Does anyone know of a more efficient approach to this task? I have researched on google but everyone uses the same technique I am.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 imagedestroy 清除与 $image 和 $image_p 关联的所有内存:
Use imagedestroy to clear any memory associated with $image and $image_p :