[英]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. 我试图在fopen之后回显图像并将其读取,但是它显示为ascii代码而不是图像格式。
I found an answer: 我找到了答案:
Fopen function opens JPEG image as text Fopen功能以文本形式打开JPEG图像
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. 我在代码中实现了header()行,但似乎它尝试将当前的php文件打开为jpg而不是图像。
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) (我不知道这是否重要,但我使用的是最新版本的XAMPP和W7)
Thanks in advance 提前致谢
If you use fopen, try 如果使用fopen,请尝试
$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. 我想知道为什么您想通过脚本而不是直接提供图像来输出图像,因为它已经是jpg图像了。
Nonetheless maybe you should try instead of echoing the file contents, using fpassthrough that outputs all remaining data on a file pointer 尽管如此,也许您应该尝试使用fpassthrough在文件指针上输出所有剩余数据,而不是回显文件内容
$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 您也可以直接使用http://php.net/manual/en/function.readfile.php调用readfile函数,而不必使用fopen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.