How to read image using 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 that is in the same directory as my code. How did I read it and assign it a variable similar to the one above?

+5
source share
2 answers

The code you entered will not read image data, but rather its file name. If you need to get an image in the same directory, you can get its contents with the help of file_get_contents()which you can use 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 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);
}

, , (, , , ), glob() jpegs, :

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

,

$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;

URL-, https://, http

0

All Articles