Features of using GD-lib on PHP hosting with limited resources

    This problem had to be dealt with after the incident on the hosting "X", on which rather small images could not be converted using this library. But the most nasty thing was that the script just died, leaving information only in the logs. Therefore, I had to find out.

    From reliable sources (logs) it was known that there was not enough memory to copy the image to it. Those. it was necessary to pre-check its sufficient availability before using the library (the option of manipulating memory_limit is not considered), predicting how much it is going to grab this memory.

    So, the GD library can create images with a palette of 2 ^ 8 colors and 2 ^ 24. T.J. theoretically, the maximum image size is 2 ^ 16 x 2 ^ 16. Total per pixel is 5 or 7 bytes.

    Let's check in practice - create square images with the createImage and createImageTrueColor functions. And we will reduce practice and theory in one graph:



    It can be seen that the results diverge, but at the same time the theory for 8 bits and the practice for 24 bits practically coincide.

    Let's try to get the empirical values ​​of “average memory consumption” per 1 pixel in two palettes. We are building graphics.



    It can be seen that for large values, they asymptotically tend to 2 and 5 bytes, respectively.

    But with small sizes of the picture (approximately 100 pixels per side) they can reach 3 and 6 bytes per pixel. We will not bother with the approximating function (although it would be worth it) and just take the average of 2.5 and 5.5 bytes per pixel, respectively.

    As a result, we get the following function of checking the possibility of using the GD library in the current operational environment:

    Copy Source | Copy HTML
    1. function returnBytes($v) {
    2.        $v = trim($v);
    3.        switch(strtolower($v[strlen($v)-1])) {
    4.            case 'g':
    5.                $v *= 1024;
    6.            case 'm':
    7.                $v *= 1024;
    8.            case 'k':
    9.                $v *= 1024;
    10.        }
    11.        return $v;
    12.     }
    13.  
    14.  
    15. function checkMemoryForGDUsage($w, $h, $trueColor = false){
    16.         return (((returnBytes(ini_get("memory_limit"))-memory_get_usage())) > ($w * $h * (2.5 + (((int)$trueColor) * 3))))?true:false;
    17.     }


    Actually everything, now the call to the checkMemoryForGDUsage function with the planned values ​​of the width, height and palette, before creating the image, can save (if successful), from fatal error.

    Also popular now: