我试图在fopen和fread之后回显图像,但它显示为ascii代码,而不是图像格式。
我找到了答案:
Fopen功能打开JPEG图像作为文本
我在代码中实现了header()行,但它似乎试图以jpg而不是图像的形式打开我当前的php文件。
这是我的代码:
$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);
(我不知道这是否重要,但我使用的是最新版本的XAMPP和W7)
提前感谢
如果使用fopen,请尝试
$fp = fopen($filename, "rb");
以强制执行二进制模式。我很懒,用这个:
$filename = $n.".jpg";
header('Content-type: image/jpg'); //without the header line I can print the ascii
echo file_get_contents($filename);
我忽略了为什么要通过脚本输出图像而不是直接提供图像的原因,因为它已经是jpg图像了。
尽管如此,也许您应该尝试使用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);
您也可以直接调用readfile函数http://php.net/manual/en/function.readfile.php无需使用fopen