通过 PHP 加载图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9959131/
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-26 07:59:05  来源:igfitidea点击:

Loading an image through PHP

phpimagemime-types

提问by Adam

I'm trying to load an image through PHP, but I don't know how. The filename is stored in the database, such as image.jpg

我正在尝试通过 PHP 加载图像,但我不知道如何。文件名存储在数据库中,如image.jpg

if($_GET['image']){
    // Client requesting image, so retrieve it from DB
    $id = mysql_real_escape_string($_GET['image']);
    $sql = "SELECT * FROM $tbl_name WHERE id = '$id' LIMIT 1";
}

The client needs to request an image like so

客户端需要像这样请求图像

http://example.com/index.php?image=1

And then it should return the image, so it can be embedded like this:

然后它应该返回图像,所以它可以像这样嵌入:

<img src="http://example.com/index.php?image=1" alt="" />

Is this possible?

这可能吗?

回答by joschua011

$img = 'path/to/image.jpg';
header('Content-Type: image/jpeg');
readfile($img);

just tested it

刚刚测试过

回答by mishu

You can use the GD library for that. You start by creating a resource using a function like http://php.net/imagecreatefromjpeg. You will need to provide the path as a parameter.

您可以为此使用 GD 库。您首先使用像http://php.net/imagecreatefromjpeg. 您需要提供路径作为参数。

After that, you just output the resource using a function like http://php.net/imagejpeg.

之后,您只需使用类似的函数输出资源http://php.net/imagejpeg

Don't forget to send the content type header, and also to use imagedestroyon the resource.

不要忘记发送内容类型标头,并imagedestroy在资源上使用。

Update:

更新:

Consider this sample:

考虑这个示例:

$im = imagecreatefromjpeg('path/to/image.jpg');
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);

回答by safarov

Here's my solution:

这是我的解决方案:

 $mime = 'image/jpg';
 $out_image = 'default.jpg'; //default no photo image
 $user_img = 'image.jpg'; //it can be gif, png, jpg

//Check if file exist in directory
if(file_exist('/path/to/'.$user_img)) {
  $s = imagesize($user_img);
  $mime = $s['mime'];
  $out_image = $img_data;
 }

 header('content-type: '.$mime);  
 readfile($img_data);

回答by David

I suggest you first make a file called image.php. So you will call image.php?id=1

我建议你先创建一个名为 image.php 的文件。所以你会调用 image.php?id=1

Have image.php header be the image type. header('Content-Type: image/jpeg');

将 image.php 标头作为图像类型。header('Content-Type: image/jpeg');

Then you can use the GDImage library in PHP to load the image, and output it. Or you can read the file and output it. The header() is key.

然后就可以使用PHP中的GDImage库来加载图片,并输出了。或者您可以读取文件并输出它。header() 是关键。