HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE

转自php manual


HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?


I worked on a script where I delt with large images. Very often the error "out of memory" occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn't find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

<?php
//-------------------------------------------------- DEFINE MAXMEM
define ("MAXMEM", 32*1024*1024);  //--- memory limit (32M) ---

//-------------------------------------------------- ENOUGH MEMORY ?
function enoughmem ($x, $y, $rgb=3) {
    return (
$x * $y * $rgb * 1.7 < MAXMEM - memory_get_usage() );
}

//-------------------------------------------------- SIMPLE EXAMPLE
list ($x, $y) = @getimagesize ('your_img.jpg');  //--- get size of img ---
if (enoughmem($x,$y)) {
   
$img = @imagecreatefromjpeg ('your_img.jpg');  //--- open img file ---
   
$thumb = 200//--- max. size of thumb ---
   
if ($x > $y) {
       
$tx = $thumb//--- landscape ---
       
$ty = round($thumb / $x * $y);
    } else {
       
$tx = round($thumb / $y * $x);  //--- portrait ---
       
$ty = $thumb;
    }
    if (
enoughmem($tx,$ty)) {
       
$thb = imagecreatetruecolor ($tx, $ty);  //--- create thumbnail ---
       
imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
       
imagejpeg ($thb, 'your_thumbnail.jpg', 80);
       
imagedestroy ($thb);
    }
   
imagedestroy ($img);
}

//--------------------------------------------------
//--- to check the memory working with           ---
//--- b/w-image or gif use:                      ---
//--------------------------------------------------
$check = enoughmem ($x, $y, 1);
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值