note 103258 deleted from function.imagecreatefromjpeg by danbrown
| From: | danbrown@php.net | Date: | Mon, 04 Apr 2011 18:11:13 +0000 |
| Subject: | note 103258 deleted from function.imagecreatefromjpeg by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178486@lists.php.net to get a copy of this message | ||
Note Submitter: petrhk at volny dot cz
----
A memory limit causes a problem with an image resizing. Function imagecopyresampled() does not
report an error for too large image. Because a server hosting usually prohibits to set memory limit,
it is better to approximate a greatest size before starting work with an image.
//Class for a calculation supposed limit of an image - depend on a memory_limit
//Returns area in count of pixels (width * height) or true for an adjustable memory limit
class calcMemForImage{
function getApproxSize(){
$IMGCONST=24;//for jpg - usual mime type
$SECURECONST=1.5;//It's minimum, it is necessary to calculate with memory for PHP script.
//See http://www.php.net/manual/en/function.imagecreatefromjpeg.php#64155
- $TWEAKFACTOR.
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
//http://php.net/manual/en/function.phpversion.php
if (!defined('PHP_VERSION_ID')) {
$version=explode('-',phpversion());
$version = explode('.', $version[0]);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}
//there is default limit 16 MB for PHP 5.2.0 and later and 8MB for previous versions
$memdef=(PHP_VERSION_ID>=50200)?16:8;
if(ini_get('memory_limit')){
//try to set memory limit
if(!ini_set( 'memory_limit',
ceil(1.1*self::return_bytes(ini_get('memory_limit'))/1048576) .'M')){
//if a limit is not adjustable
return ceil((self::return_bytes( ini_get('memory_limit')) -
65536)/$IMGCONST/$SECURECONST);
}else {
//if a limit is adjustable back to the original limit
ini_set( 'memory_limit', ini_get('memory_limit'));
return true;//if memory limit is adjustable
}
}//if ini_get('memory_limit') does not work
else return ceil(($memdef*1048576-65536)/$IMGCONST / $SECURECONST);
}
//http://www.php.net/manual/en/function.ini-get.php#96996
function return_bytes ($size_str){
switch (substr ($size_str, -1)){
case 'M': case 'm': return (int)$size_str * 1048576;
case 'K': case 'k': return (int)$size_str * 1024;
case 'G': case 'g': return (int)$size_str * 1073741824;
default: return $size_str;
}
}
}
//example
$w=new calcMemForImage();
echo $w->getApproxSize();