Search code examples
phpzlibimage-compression

php image data compress with ob_gzhandler not working


When I'm trying to use readfile with ob_gzhandler I'm getting in browser:

Content Encoding Error

my code is

function enableCompression()
{
    $ok = ob_gzhandler('', PHP_OUTPUT_HANDLER_START);
    if ($ok === FALSE) {
        return FALSE; // not allowed
    }

    if (function_exists('ini_set')) {
        ini_set('zlib.output_compression', 'Off');
        ini_set('zlib.output_compression_level', '6');
    }
    ob_start('ob_gzhandler', 1);
    return TRUE;
}

enableCompression(); //returns TRUE

$file = "pathto/default.png";
$info = @getimagesize($file);
header('Content-type: ' . $info['mime']);

readfile($file);
exit;

When I comment header('Content-type: ' . $info['mime']); line, I see image data like this in browser

�PNG IHDR��J�TPLTE��ސ�������������ؑ��������vvv�����䀀�� ...."

Am I doing something wrong? Is it possible to compress image data with usage ob_gzhandler?

PS: zlib is installed all is working, other website data is normally outputed. Only compressed image resizer is not working.


Solution

  • I think the mis-encoding issue you're seeing is related to the fact you're calling ob_gzhandler() directly. It's not intended to be called directly. If you need to see if ob_gzhandler is supported you can test like this:

    if(!ob_start('ob_gzhandler')) {
        die('ob_gzhandler not supported');
    }
    

    After making that change the Content-Type header was fixed and the image displayed correctly. The content didn't come out compressed though.

    It appears that if you send the Content-Type: image/png header after you start the output buffer it causes ob_gzhandler to not compress the output buffer. This worked for me:

    header('Content-type: image/png');
    ob_start('ob_gzhandler');
    readfile('test.png');
    ob_end_flush();
    

    While this didn't:

    ob_start('ob_gzhandler');
    header('Content-type: image/png');
    readfile("test.png");
    ob_end_flush();
    

    That being said, normally it's a bad idea to compress PNG files (or JPEG, GIF, etc) since they're already compressed and probably can't be compressed very much better. Is there a reason you're trying to double compress a PNG file?