Possible Duplicate:
PHP rebuilding images: memory usage
I have a simple image upload script. A user is allowed to upload an image (gif,jpg or png) with a max file size of 10MB. The user is also allowed to apply a crop to the image, so I set the memory limit on the script to 256MB. I figured 256MB was more then enough memory to crop a 10MB image. I was wrong. When a user uploads a large image (around 5000x5000) and barely crops it, the script always throws an out of memory error. I found this neat tool to help determine the memory limit when resizing an image with php. I also came across this formula
$width * $height * $channels * 1.7
to determine how much memory an image will require. I am looking for someone to explain what is going on here. It is pretty clear to me that a 10MB jpeg is not 10MB when loaded into memory, but how can I determine how much memory it will take up? Is the formula above correct? And is there a more efficent way to crop large images or do I have to use massive amounts of memory?
For anyone interested, here is the code to crop an image.
function myCropImage(&$src, $x, $y, $width, $height) {
$src_width = imagesx($src);
$src_height = imagesy($src);
$max_dst_width = 1024;
$dst_width = $width;
$dst_height = $height;
$max_dst_height = 768;
// added to restrict size of output image.
// without this check an out of memory error is thrown.
if($dst_width > $max_dst_width || $dst_height > $max_dst_height) {
$scale = min($max_dst_width / $dst_width, $max_dst_height / $dst_height);
$dst_width *= $scale;
$dst_height *= $scale;
}
if($x < 0) {
$width += $x;
$x = 0;
}
if($y < 0) {
$height += $y;
$y = 0;
}
if (($x + $width) > $src_width) {
$width = $src_width - $x;
}
if (($y + $height) > $src_height) {
$height = $src_height - $y;
}
$temp = imagecreatetruecolor($dst_width, $dst_height);
imagesavealpha($temp, true);
imagefill($temp, 0, 0, imagecolorallocatealpha($temp, 0, 0, 0, 127));
imagecopyresized($temp, $src, 0, 0, $x, $y, $dst_width, $dst_height, $width, $height);
return $temp;
}