【问题标题】:How can I render a remote image with php?如何使用 php 渲染远程图像?
【发布时间】:2012-09-19 17:06:39
【问题描述】:

这是 jpg:http://i.stack.imgur.com/PIFN0.jpg

假设我希望从/img.php?file_name=PIFN0.jpg 渲染此内容

这就是我尝试完成这项工作的方式:

/sample.php

<p>Here's my image:</p>
<img src="/img.php?file_name=PIFN0.jpg">

/img.php

<?php
    $url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
    header('Content-type: image/jpeg');
    imagejpeg($url);
?>

我希望/sample.php 显示图像。但这不起作用。我得到的只是一个破碎的图像。我做错了什么?

【问题讨论】:

    标签: php image header http-headers


    【解决方案1】:

    使用imagecreatefromjpeg:

    <?php
        $url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
        header('Content-type: image/jpeg');
        imagejpeg(imagecreatefromjpeg($url));
    ?>
    

    参考http://php.net/manual/en/function.imagecreatefromjpeg.php

    【讨论】:

    • 嗯 - 我没有意识到 imagecreatefromjpeg() 及其同类支持 fopen() 包装器。
    • 是的 :) 很酷的东西 - 我想最终还是得有人设置它
    • 致 OP:当然,这并不能保证图像所在的服务器实际上允许您通过 PHP 下载它并重新提供它。
    • 如果您有混合的 jpg ng 和 gif 格式怎么办?
    【解决方案2】:
    <?php
    header("Content-Type: image/jpeg");
    $url = "http://i.stack.imgur.com/PIFN0.jpg";
    $imgContents = file_get_contents($url);
    $image = @imagecreatefromstring($imgContents);
    imagejpeg($image);
    ?>
    

    【讨论】:

      【解决方案3】:

      这是一个工作示例:

      <?php
      function img_create($filename, $mime_type) 
      {  
        $content = file_get_contents($filename);
        $base64   = base64_encode($content); 
        return ('data:' . $mime_type . ';base64,' . $base64);
      }
      ?>
      
      <img src="<?php print img_create('http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png','image/png'); ?>" alt="random logo" />
      

      【讨论】:

        【解决方案4】:

        无需使用GD函数:

        <?php
            $url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
            header('Content-type: image/jpeg');
            readfile($url);
        ?>
        

        【讨论】:

          【解决方案5】:
          header('Content-type: image/jpeg');
          readfile($_GET['id']);
          

          但是在新服务器上,只能读取本地图片,远程图片出错。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-10-16
            • 1970-01-01
            • 2019-02-11
            • 2012-06-17
            • 2015-09-02
            • 2020-10-12
            • 2014-01-25
            相关资源
            最近更新 更多