在php中调整多个图像的大小而不超出内存限制

发布于 2024-12-26 15:44:40 字数 745 浏览 5 评论 0原文

我目前正在尝试获取一个表单,该表单允许使用 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 技术交流群。

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

发布评论

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

评论(1

云胡 2025-01-02 15:44:40

使用 imagedestroy 清除与 $image 和 $image_p 关联的所有内存:

$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);
imagedestroy($image);
imagedestroy($image_p);

Use imagedestroy to clear any memory associated with $image and $image_p :

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