Search code examples
phpget

Issue while trying to display a remote image (GET php) - corrupt/empty image


I'd like to display some remote images from a php url with a GET method (3 parameters: Key, ImageID, Size). E.g: http://www.example.com/getImage?Key=thekey&ImageId=2&Size=1

I followed this one: https://stackoverflow.com/a/12629513 (replacing the content-type with jpeg), tried with a random jpeg image on the net and it worked.

However, when I try this method with my php url: the file is corrupted.

<?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://www.example.com/getImage?Key=thekey&ImageId=2&Size=1','image/jpeg'); ?>" alt="random logo" />

Any idea..?


Solution

  • Try this:

    <?php
    
    function img_create($filename, $mime_type) { 
       $content = file_get_contents($filename); 
       $base64   = base64_encode($content);
       $src_string = 'data:'.$mime_type.';base64,'.$base64;
       echo $src_string;
    }
    ?>
    
    <img src="<?php img_create('http://www.example.com/getImage?Key=thekey&ImageId=2&Size=1','image/jpeg'); ?>" alt="random logo" />