php 计算图片像素使用内存大小
有时直接使用imagecreatefromjpeg 生成新的图片会报错,例如:
<?php imagecreatefromjpeg('1.jpg');//图片的尺寸是4962 X 7019 大小0.99M
就会报错
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 19848 bytes) in D:\phpStudy\WWW\api.php on line 2
然后判断是否超内存,者解决问题
function is_image_pixel($file_path){
$img = getimagesize($file_path);
$max_width=$img_width=$img[0];
$max_height=$img_height=$img[1];
$memory =(int)ini_get('memory_limit');
$scale = min(
$max_width / $img_width,
$max_height / $img_height
);
$new_width = $img_width * $scale;//计算要缩小的宽值
$new_height = $img_height * $scale;//就算要缩小的高度值
$memimg = ($new_width*$new_height*$img['channels'] + $img[0]*$img[1]*$img['channels']) * 1.7/ 1024 / 1024 ;
//echo $memimg;exit;
if($memory > $memimg){ //判断是否超过php.ini 设定的内存值
return true;
}else{
return false;
}
}
$file_path='1.jpg';
if(is_image_pixel($file_path)){//判断是否超内存,不超则创建新图片
imagecreatefromjpeg($file_path);
}
这网站可以看图片内存要使用的情况:http://www.dotsamazing.com/en/labs/phpmemorylimit