简体   繁体   中英

imagecreatefromstring failed when large image

I have a code for crop uploaded image.

$fh = fopen($source, "rb") or die();
$buffer = 1024*1024;
while (!feof($fh)) { 
  $freadedimage=fread($fh, $buffer); 
  flush();
}
fclose($fh);

$sourceImg = imagecreatefromstring($freadedimage);
if ($sourceImg === false) {
  throw new Exception("Invalid image.");
}

When file is not so big (approx. 300-900 Kb) all gone excellent. But, when file size is more than 2 Mb I got the error:

Warning: imagecreatefromstring(): Data is not in a recognised format

I tried to use file_get_contents instead of fread - works perfectly. But only in case of ini_set('memory_limit', '64M' ). But this variant is not for me, because I have a restrictions on host.

Thanks for any help guys!

You're reading the file in chunks of 1024*1024 bytes, but if the file is larger than that then each iteration of the loop is overwriting what has already been read

$freadedimage = '';
while (!feof($fh)) { 
    $freadedimage .= fread($fh, $buffer); 
    flush();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM