How can I render a remote image with php?

2020-06-06 04:27发布

Here's a jpg: http://i.stack.imgur.com/PIFN0.jpg

stackoverflow logo jpg

Let's say I'd like this rendered from /img.php?file_name=PIFN0.jpg

Here's how I'm trying to make this work:

/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);
?>

I would expect /sample.php to show the image. But this doesn't work. All I get is a broken image. What am I doing wrong?

5条回答
叛逆
2楼-- · 2020-06-06 05:02
<?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楼-- · 2020-06-06 05:07

No need to use the GD functions:

<?php
    $url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
    header('Content-type: image/jpeg');
    readfile($url);
?>
查看更多
Viruses.
4楼-- · 2020-06-06 05:08

Use imagecreatefromjpeg:

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

Reference: http://php.net/manual/en/function.imagecreatefromjpeg.php

查看更多
看我几分像从前
5楼-- · 2020-06-06 05:08
header('Content-type: image/jpeg');
readfile($_GET['id']);

but in the new server, only can read the local images, the remote images is error.

查看更多
淡お忘
6楼-- · 2020-06-06 05:11

Here is an working example:

<?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" />
查看更多
登录 后发表回答