【问题标题】:Show image using file_get_contents使用 file_get_contents 显示图像
【发布时间】:2011-05-16 06:14:21
【问题描述】:

如何在 php 中显示使用 file_get_contents 检索到的图像?

我是否需要修改标题并只是回显它或其他什么?

谢谢!

【问题讨论】:

    标签: php http-headers file-get-contents


    【解决方案1】:

    我是否需要修改标题并只是回显它或其他什么?

    没错。

    之后发送header("content-type: image/your_image_type"); 和数据。

    【讨论】:

    • 好吧,还有 Header("Content-Type: image/jpg");应该够了吧?
    • @Belgin 如果是 JPG 图片,是的。
    • 不需要图片/jpeg 吗?
    【解决方案2】:

    你可以这样做,或者你可以使用readfile函数,它会为你输出:

    header('Content-Type: image/x-png'); //or whatever
    readfile('thefile.png');
    die();
    

    编辑:Derp,修正了明显的错字。

    【讨论】:

      【解决方案3】:

      您可以使用readfile 并输出您可以从getimagesize 获取的图像标题,如下所示:

      $remoteImage = "http://www.example.com/gifs/logo.gif";
      $imginfo = getimagesize($remoteImage);
      header("Content-type: {$imginfo['mime']}");
      readfile($remoteImage);
      

      您应该在此处使用 readfile 的原因是它将文件直接输出到输出缓冲区,因为file_get_contents 会将文件读入内存,这在此内容中是不必要的,并且对于大文件可能很密集。

      【讨论】:

      • 此解决方案要好得多,因为图像标题是动态传递的。虽然我确实发现了一个问题:在我的 PHP 版本中,第三行(标题行)的语法不被接受。这虽然有效: header("Content-type: ".$imginfo['mime']);
      • 对于那些收到错误“图像无法显示”或只是“空屏”的用户。只需使用
      【解决方案4】:

      你可以这样做:

      <?php
          $file = 'your_images.jpg';
      
          header('Content-Type: image/jpeg');
          header('Content-Length: ' . filesize($file));
          echo file_get_contents($file);
      ?>
      

      【讨论】:

        【解决方案5】:
        $image = 'http://images.itracki.com/2011/06/favicon.png';
        // Read image path, convert to base64 encoding
        $imageData = base64_encode(file_get_contents($image));
        
        // Format the image SRC:  data:{mime};base64,{data};
        $src = 'data: '.mime_content_type($image).';base64,'.$imageData;
        
        // Echo out a sample image
        echo '<img src="' . $src . '">';
        

        【讨论】:

        • 我用它来让谷歌静态地图在 Safari 和 Chrome 中运行,完美运行。
        【解决方案6】:

        对@seengee 答案的小编辑: 为了工作,你需要在变量周围加上花括号,否则你会得到一个错误。

        header("Content-type: {$imginfo['mime']}");

        【讨论】:

          猜你喜欢
          • 2013-09-25
          • 2012-09-16
          • 1970-01-01
          • 1970-01-01
          • 2011-08-18
          • 2012-11-07
          • 2015-11-21
          • 2013-02-25
          • 2013-02-07
          相关资源
          最近更新 更多