PHP允许内存使用耗尽,而我看不到任何迹象


PHP allowed memory usage exhausted while I see no sign of it

我有一个简单的PHP脚本,它只包含以下几行

$mem = memory_get_usage()/1024;
$mem = $mem/1024;
echo "mem: ".$mem ."Mb<br>";
$max =  ini_get('memory_limit');
echo "max is $max<br>";
$filename = 'upload/orig/CID_553.jpg';              
$filesize = (filesize($filename) / 1024);
echo "filesize is $filesize Kb<br>";        
$img_pointer = imagecreatefromjpeg($filename);

当运行它时,我得到这个输出

mem: 0.30711364746094Mb
max is 64M
filesize is 952.2666015625 Kb
Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 13056 bytes) in C:'temp_checkmem.php on line 13 

加载一个952Kb的文件会让PHP(imagecreatefrompeg)超过允许的64Mb内存,这怎么可能呢?有什么想法吗?

仅仅因为JPG文件只有952k字节并不意味着它不能占用VERY大量内存,例如,使用2048x2048纯白图像进行简单测试会生成59kbyte.JPG文件。

该文件将解压缩为GD.中的2048x2048x3 = 12.6兆字节原始位图

您可以粗略估计GD加载/解压缩图像所需的内存:

$stats = getimagesize($filename);
$memory_estimate = $stats[0] * $stats[1] * 3; // height * width * 3 bytes per pixel
echo "{$stats[0]}x{$stats[1]} -> {$memory_estimate} bytes";

原始图片或图片的内部格式可能超过内存限制。

试着加载一张大图并将其保存为位图,它非常巨大。。

每个像素取3字节(24位彩色模式),0-255 red0-255 green0-255 blue

在使用额外的alpha通道imagealphablending();打开文件时,每个像素有4个字节(32位颜色模式),从而生成额外的0-255 for alpha blending

2,5 MB JPG (100% quality) ~ 36,0 MB bitmap - 12 megapixel    
4,1 MB JPG (100% quality) ~ 96,0 MB bitmap - 32 megapixel

与此工具相比:

http://web.forret.com/tools/megapixel.asp

请参阅wikipedia:

http://en.wikipedia.org/wiki/True_Color#True_color_.2824-bit.29