繁体   English   中英

PHP-将图像作为jpg而不是ASCII回显

[英]PHP - echo image as jpg not ascii

我试图在fopen之后回显图像并将其读取,但是它显示为ascii代码而不是图像格式。

我找到了答案:

Fopen功能以文本形式打开JPEG图像

我在代码中实现了header()行,但似乎它尝试将当前的php文件打开为jpg而不是图像。

这是我的代码:

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

您也可以直接使用http://php.net/manual/en/function.readfile.php调用readfile函数,而不必使用fopen

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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