Lafdoma
Lafdoma

Reputation: 51

PHP - Read an image with URL

Here my problem, I do a query to MySQL (PDO) for give me the last 5 URLs of a table nammed avatar who contains the ID and the URL :

$response = $dbh->query("SELECT url FROM avatar ORDER BY id_URL DESC LIMIT 0,5 ");

And I did :

  while ($donnees = $response->fetch())
{

$urlImage = $donnees['url']; //'url' contains the URL
$result = file_get_contents($urlImage);        
header('Content-Type: image/png');
echo $result;   
?>

But the header just return a small empty white square. However, the "$result = file_get_contents($urlImage);" takes properly the URL because when I do :

   $urlImage = $donnees['url']; //'url' contains the URL
$result = file_get_contents($urlImage);        
echo $result;   
?>

It just shows the "encodage of the image" (a ton of special characters) but not displays the image.

I also try with "imagick" but it says to me that the class doesn't exist and I don't think that the imagecreatefrompng can be use with URL.

Thanks !

Upvotes: 0

Views: 125

Answers (2)

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

Can you try this and see if it works?

 $image = file_get_contents($donnees['url']);
 $finfo = new finfo(FILEINFO_MIME_TYPE);
 header('content-type: ' . $finfo->buffer($image));
 echo $image;

This is suppose to handle one Image. One php script can return one image. If you want to combine the images and render a big long image then probably you should look at http://image.intervention.io/

EDIT

What I understood after trying out the above code is that if you put file_get_contents before header then the raw characters are shown. However you put it after header then everything seems to be working

$image="http://www.hillspet.com/HillsPetUS/v1/portal/en/us/cat-care/images/HP_PCC_md_0130_cat53.jpg";
$filename = basename($image);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpeg"; break;
    default:
}

header('Content-type: ' . $ctype);
$image = file_get_contents($image);
echo $image;

Working fiddle

Upvotes: 3

Altimus Prime
Altimus Prime

Reputation: 2337

If you're trying to use a dynamic image source where your url is the image source, and it isn't working, then the problem might be that there's a space or extra character somewhere on the page, which will make the browser treat it like a document instead of an image in some cases.

Your problem is that the browser isn't understanding that it's supposed to be an image.

You could always do:

<img src="<?=$urlImage?>">

Upvotes: 1

Related Questions