1

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();
}
unloco
  • 6,928
  • 2
  • 47
  • 58
  • A PNG should not get (re)encoded, not as UTF8 and not as ANSI. Both are text encodings, and PNG files are binary. – Jongware May 15 '15 at 19:10
  • That's really the problem as readfile seems to be enconding the contents! Is there a solution to avoid that? The project was deployed on several other servers but this is the first ocurrence of the issue – unloco May 15 '15 at 19:28
  • 1
    Have you tried setting `header('Content-Transfer-Encoding: binary');` and `header('Content-Description: File Transfer');`? – VolenD May 15 '15 at 22:45

1 Answers1

1

You can try adding to your response some additional headers:

header('Content-Transfer-Encoding: binary');
header('Content-Description: File Transfer');
VolenD
  • 3,592
  • 18
  • 23