如何检查jpeg是否适合内存? [英] How can I check if a jpeg will fit in memory?

查看:101
本文介绍了如何检查jpeg是否适合内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 imagecreatefromjpeg 打开JPEG图像很容易导致致命错误,因为所需的内存会执行 memory_limit

Opening a JPEG image using imagecreatefromjpeg can easily lead to fatal errors, because the memory needed exeeds the memory_limit.

小于100Kb的 .jpg 文件很容易超过2000x2000像素 - 大约需要20个像素打开时-25MB内存使用不同的压缩级别,相同的2000x2000px映像可能占用磁盘上的5MB。

A .jpg file that is less than 100Kb in size can easily exceed 2000x2000 pixels - which will take about 20-25MB of memory when opened. "The same" 2000x2000px image may take up 5MB on the disk using a different compression level.

所以我显然无法使用filesize来确定它是否可以安全打开。

So I obviously cannot use the filesize to determine if it can be opened safely.

如何确定某个文件是否适合之前 打开它,这样我就可以避免致命错误了?

How can I determine if a file will fit in memory before opening it, so I can avoid fatal errors?

推荐答案

根据几个来源,所需的内存最多为每个像素5个字节,具体取决于几个不同的因素,如位深度。我自己的测试证实这大致是正确的。

According to several sources the memory needed is up to 5 bytes per pixel depending on a few different factors such as bit-depth. My own tests confirm this to be roughly true.

除此之外还有一些需要考虑的开销。

On top of that there is some overhead that needs to be accounted for.

但是通过检查图像尺寸 - 可以在不加载图像的情况下轻松完成 - 我们可以粗略估计所需的内存并将其与(估计)可用内存进行比较,如下所示:

But by examining the image dimensions - which can easily be done without loading the image - we can roughly estimate the memory needed and compare it with (an estimate of) the memory available like this:

$filename = 'black.jpg';

//Get image dimensions
$info = getimagesize($filename);

//Each pixel needs 5 bytes, and there will obviously be some overhead - In a
//real implementation I'd probably reserve at least 10B/px just in case.
$mem_needed = $info[0] * $info[1] * 6;

//Find out (roughly!) how much is available
// - this can easily be refined, but that's not really the point here
$mem_total = intval(str_replace(array('G', 'M', 'K'), array('000000000', '000000', '000'), ini_get('memory_limit')));

//Find current usage - AFAIK this is _not_ directly related to
//the memory_limit... but it's the best we have!
$mem_available = $mem_total - memory_get_usage();

if ($mem_needed > $mem_available) {
    die('That image is too large!');
}

//Do your thing
$img = imagecreatefromjpeg('black.jpg');

这只是表面上的测试,所以我建议用进行进一步的测试的不同图像,并使用这些函数检查您的特定环境中的计算是否正确:

This is only tested superficially, so I'd suggest further testing with a lot of different images and using these functions to check that the calculations are fairly correct in your specific environment:

//Set some low limit to make sure you will run out
ini_set('memory_limit', '10M');

//Use this to check the peak memory at different points during execution
$mem_1 = memory_get_peak_usage(true);

这篇关于如何检查jpeg是否适合内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆