3

I want to show image with php script. Here is my current code:

<?php
if (isset ($_GET['id'])) $id = $_GET['id'];
$t=getimagesize ($id) or die('Unknown type of image');

switch ($t[2])
{
    case 1:
    $type='GIF';
    $img=imagecreatefromgif($path);
    break;
    case 2:
    $type='JPEG';
    $img=imagecreatefromjpeg($path);
    break;
    case 3:
    $type='PNG';
    $img=imagecreatefrompng($path);
    break;
}

header("Content-type: image/".$type);
echo $img;
?>

But it doesn't show the image. What is the right way instead of echo $img?

Max Frai
  • 61,946
  • 78
  • 197
  • 306

4 Answers4

4

just like this :

public function getImage()
{

    $imagePath ="img/wall_1.jpg";

    $image = file_get_contents(imagePath );
            header('content-type: image/gif');
            echo $image;

}
Aouidane Med Amine
  • 1,571
  • 16
  • 17
3
header("Content-type: image/jpeg");
imagejpeg($img);
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • ` Warning: imagejpeg(): supplied argument is not a valid Image resource` to the second line of your code – Max Frai May 19 '11 at 12:16
  • The question asks about **return** image... IMHO, the answer of this guy is the way to go: [link](https://stackoverflow.com/questions/22266402/how-to-encode-an-image-resource-to-base64)... that combined with this another [link](https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html) must do the job. – Nowdeen Jul 25 '17 at 13:16
2

There are functions for each format.

In your case you could add:

switch ($t[2])
{
    case 1:
    imagegif($img);
    break;
    case 2:
    imagejpeg($img);
    break;
    case 3:
    imagepng($img);
    break;
}
ySgPjx
  • 10,165
  • 7
  • 61
  • 78
0

I've used echo() for this before and it's worked. But try using imagejpeg() function instead.

Also, make sure you don't have any other content being output either before or after the image in your script. A common problem is blank spaces and line feeds being output caused by space and line feeds before or after the <?php and ?> tags. You need to remove all of these. And check any other PHP code loaded via include() or requre() for the same thing.

Spudley
  • 166,037
  • 39
  • 233
  • 307