How to read an image with PHP?

2020-07-11 07:48发布

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?

标签: php image
2条回答
霸刀☆藐视天下
2楼-- · 2020-07-11 08:18

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

查看更多
狗以群分
3楼-- · 2020-07-11 08:32

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;
}
查看更多
登录 后发表回答