2015-11-07 195 views
0

我有一个小的PHP脚本,它将图像文件转换为缩略图。我有一个100MB的最大上传者,我想保留。获取未压缩的图像大小

问题是,当打开文件时,GD解压缩它,导致它很大,并导致PHP内存不足(Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 64000 bytes))。我不想增加我的记忆比这允许的大小。

我不关心图像,我可以让它显示一个默认缩略图,没关系。但我确实需要一种方法来捕捉图像太大时产生的错误imagecreatefromstring(file_get_contents($file))。由于生成的错误是致命的,因此无法尝试捕获,并且由于它将其加载到一个命令中,所以我无法继续关注它以确保它不会接近极限。在尝试处理图像之前,我需要一种方法来计算图像的大小。

有没有办法做到这一点? filesize不会工作,因为它给了我压缩后的大小...

我的代码如下:

$image = imagecreatefromstring(file_get_contents($newfilename)); 
$ifilename = 'f/' . $string . '/thumbnail/thumbnail.jpg'; 

$thumb_width = 200; 
$thumb_height = 200; 

$width = imagesx($image); 
$height = imagesy($image); 

$original_aspect = $width/$height; 
$thumb_aspect = $thumb_width/$thumb_height; 

if ($original_aspect >= $thumb_aspect) 
{ 
    // Image is wider than thumbnail. 
    $new_height = $thumb_height; 
    $new_width = $width/($height/$thumb_height); 
} 
else 
{ 
    // Image is taller than thumbnail. 
    $new_width = $thumb_width; 
    $new_height = $height/($width/$thumb_width); 
} 

$thumb = imagecreatetruecolor($thumb_width, $thumb_height); 

// Resize and crop 
imagecopyresampled($thumb, 
        $image, 
        0 - ($new_width - $thumb_width)/2, // Center the image horizontally 
        0 - ($new_height - $thumb_height)/2, // Center the image vertically 
        0, 0, 
        $new_width, $new_height, 
        $width, $height); 
imagejpeg($thumb, $ifilename, 80); 

回答

0

试图重新上浆之前看原始图像的大小?也许把它乘以基于平均格式压缩的设定百分比?

$averageJPGFileRatio = 0.55; 
$orgFileSize = filesize ($newfilename) * 0.55; 

并在做任何工作之前看这个?

二次想法

计算的话是这样的:width * height * 3 = filesize 3是红色,绿色和蓝色的值,如果你处理图像alpha通道的使用4,而不是3,这应该给你非常接近估计位图大小。不考虑标题信息,但在几个字节应该忽略不计。

+0

这似乎工作,非常感谢! – none