Reputation: 31
I am trying to echo an image after fopen and fread it, but it shows as ascii code not as image format.
I found an answer:
Fopen function opens JPEG image as text
I implemented the header() line in my code but it seems that it try to open my current php file as jpg not the image.
Here is my code:
$filename = $n.".jpg";
//echo $n.'.jpg'; prints image_name.jpg
$fp = fopen($filename, "r");
$data = fread($fp, filesize($filename));
header('Content-type: image/jpg'); //without the header line I can print the ascii
echo $data; //I want to print my $data as image format not ascii
fclose($fp);
(I don't know if it does matter but I am using latest version of XAMPP and W7)
Thanks in advance
Upvotes: 0
Views: 561
Reputation: 290
I miss the point why you want to output the image through a script instead of serving it directly, since it is already a jpg image.
Nonetheless maybe you should try instead of echoing the file contents, using fpassthrough that outputs all remaining data on a file pointer
$filename = $n.".jpg";
$fp = fopen($filename, "r");
header('Content-type: image/jpg'); //without the header line I can print the ascii
fpassthru($fp)
fclose($fp);
You may also call readfile function directly http://php.net/manual/en/function.readfile.php without having to use fopen
Upvotes: 0
Reputation: 1808
If you use fopen, try
$fp = fopen($filename, "rb");
to enforce binary mode. I'm lazy and use this:
$filename = $n.".jpg";
header('Content-type: image/jpg'); //without the header line I can print the ascii
echo file_get_contents($filename);
Upvotes: 1