How can I render a remote image with php?
17,258
Solution 1
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
Solution 2
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" />
Solution 3
No need to use the GD functions:
<?php
$url = 'http://i.stack.imgur.com/' . $_GET['file_name'];
header('Content-type: image/jpeg');
readfile($url);
?>
Related videos on Youtube
Author by
Ryan
BY DAY: Ninja. BY NIGHT: Ninja. FOR FUN: "If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers
Updated on June 04, 2022Comments
-
Ryan almost 2 years
Here's a jpg:
http://i.stack.imgur.com/PIFN0.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? -
Michael Berkowski over 11 yearsHuh - I didn't realize imagecreatefromjpeg() and its ilk supported the fopen() wrappers.
-
Daniel Li over 11 yearsYep :) cool stuff - I guess someone had to set it up eventually
-
Michael Berkowski over 11 yearsTo the OP: Of course, this doesn't guarantee that the server on which the image resides will actually allow you to download it via PHP and re-serve it.
-
Kevin almost 10 yearswhat if you have a mix of jpg ng anf gifs?