user1259962
user1259962

Reputation:

How to read an image with PHP?

i know that

$localfile = $_FILES['media']['tmp_name'];

will get the image given that the POST method was used. I am trying to read an image which is in the same directory as my code. How do i read it and assign it to a variable like the one above?

Upvotes: 8

Views: 39679

Answers (2)

Raj Nandan Sharma
Raj Nandan Sharma

Reputation: 3862

If you want to read an image and then render it as an image

$image="path-to-your-image"; //this can also be a url
$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;

If your path is a url, and it is using https:// protocol then you might want to change the protocol to http

Working fiddle

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270767

The code you posted will not read the image data, but rather its filename. If you need to retrieve an image in the same directory, you can retrieve its contents with file_get_contents(), which can be used to directly output it to the browser:

$im = file_get_contents("./image.jpeg");
header("Content-type: image/jpeg");
echo $im;

Otherwise, you can use the GD library to read in the image data for further image processing:

$im = imagecreatefromjpeg("./image.jpeg");
if ($im) {
  // do other stuff...
  // Output the result
  header("Content-type: image/jpeg");
  imagejpeg($im);
}

Finally, if you don't know the filename of the image you need (though if it's in the same location as your code, you should), you can use a glob() to find all the jpegs, for example:

$jpegs = glob("./*.jpg");
foreach ($jpegs as $jpg) {
  // print the filename
  echo $jpg;
}

Upvotes: 15

Related Questions