gpt4 book ai didi

php - 如何检查 jpeg 是否适合内存?

转载 作者:可可西里 更新时间:2023-10-31 23:01:16 26 4
gpt4 key购买 nike

使用 imagecreatefromjpeg 打开 JPEG 图像很容易导致 fatal error ,因为所需的内存超出了 memory_limit

小于 100Kb 的 .jpg 文件很容易超过 2000x2000 像素 - 打开时将占用大约 20-25MB 的内存。使用不同的压缩级别,“相同的”2000x2000 像素图像可能会占用 5MB 的磁盘空间。

所以我显然不能用filesize来判断是否可以安全打开。

如何在打开文件之前确定文件是否适合内存,从而避免 fatal error ?

最佳答案

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

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

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

$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');

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

//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);

关于php - 如何检查 jpeg 是否适合内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46798454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com