Search code examples
phpencodingpngphp-gd

PHP: PNG readfile encoding issue


I have this code which outputs a PNG file to the browser

header('Content-type: image/png');
header("Content-Length: " . filesize($cache_file));
readfile($cache_file);
exit();

The file $cache_file was saved like this

imagepng(self::$image, self::$cache);

The browser is displaying a broken image. When I download it and open it with npp, I find that it's encoded in UTF-8, so I change the encosing to ANSI and it displays correctly on windows explorer

What could be causing this encoding issue? how can I fix it when saving or reading the file?

Edit: When I open the PNG directly on the browser, it displays correctly which means that the issue is ocurring at the level of readfile This is not my server, so what server setting should I check/modify?

Solution: I used imagepngto output the image content

public static function outputPNG($file)
{
    //clear any previous buffer
    ob_clean();
    ob_end_clean();
    header('Content-type: image/png');
    //i will be only outputting PNG images
    $im = imagecreatefrompng($file);
    imagesavealpha($im, true);
    imagealphablending($im, true);
    imagepng($im);
    exit();
}

Solution

  • You can try adding to your response some additional headers:

    header('Content-Transfer-Encoding: binary');
    header('Content-Description: File Transfer');