如何用PHP读取图像? [英] How to read an image with PHP?

查看:84
本文介绍了如何用PHP读取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道

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

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

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?

推荐答案

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

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;

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

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);
}

最后,如果你不知道你需要的图像的文件名(虽然如果它与你的代码在同一个位置,你应该),你可以使用 glob()来查找所有的jpeg,例如:

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

这篇关于如何用PHP读取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆