【问题标题】:PHP - echo image as jpg not asciiPHP - 将图像回显为 jpg 而不是 ascii
【发布时间】:2014-12-07 19:05:45
【问题描述】:

我试图在 fopen 之后回显图像并对其进行 fread,但它显示为 ascii 代码而不是图像格式。

我找到了答案:

Fopen function opens JPEG image as text

我在代码中实现了 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)

提前致谢

【问题讨论】:

  • 这可能是您浏览器的缓存问题。尝试真正刷新页面请求。
  • 这段代码对我来说没有任何修改。

标签: php image echo


【解决方案1】:

我想念为什么要通过脚本输出图像而不是直接提供图像,因为它已经是 jpg 图像。

尽管如此,也许您应该尝试使用 fpassthrough 来代替回显文件内容,该 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

【讨论】:

    【解决方案2】:

    如果你用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多