简体   繁体   中英

PHP - echo image as jpg not ascii

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM