How to check if jpeg is suitable in memory?

Opening a JPEG image using imagecreatefromjpegcan lead to fatal errors because memory is required for memory_limit.

A file .jpgof less than 100 KB can easily exceed 2000x2000 pixels - it will take about 20-25 MB of memory when opened. "The same 2000x2000px image can take up to 5 MB on disk using a different compression level.

Therefore, I obviously cannot use the file size to determine if it can be opened safely.

How to determine if a file will fit in memory before to open it, so I can avoid fatal errors?

+4
source share
1 answer

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 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 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);
+4

Source: https://habr.com/ru/post/1687677/


All Articles