如何使用 PHP 读取图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10034255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:11:33  来源:igfitidea点击:

How to read an image with PHP?

phpimage

提问by Michael Berkowski

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?

鉴于使用了 POST 方法,将获得图像。我正在尝试读取与我的代码位于同一目录中的图像。我如何阅读它并将其分配给像上面那样的变量?

回答by Michael Berkowski

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:

您发布的代码不会读取图像数据,而是读取其文件名。如果需要检索同目录下的图片,可以使用 检索其内容file_get_contents(),可以直接输出到浏览器:

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

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

否则,您可以使用GD 库读取图像数据以进行进一步的图像处理:

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

Finally, if you don't knowthe 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:

最后,如果您不知道所需图像的文件名(尽管如果它与您的代码位于同一位置,您应该知道),您可以使用 aglob()来查找所有 jpeg,例如:

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

回答by Raj Sharma

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

如果您的路径是一个 url,并且它使用的是 https:// 协议,那么您可能希望将协议更改为 http

Working fiddle

工作小提琴