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);
?>
Share:
17,258

Related videos on Youtube

Ryan
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, 2022

Comments

  • Ryan
    Ryan almost 2 years

    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?

  • Michael Berkowski
    Michael Berkowski over 11 years
    Huh - I didn't realize imagecreatefromjpeg() and its ilk supported the fopen() wrappers.
  • Daniel Li
    Daniel Li over 11 years
    Yep :) cool stuff - I guess someone had to set it up eventually
  • Michael Berkowski
    Michael Berkowski over 11 years
    To 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
    Kevin almost 10 years
    what if you have a mix of jpg ng anf gifs?