php 使用 file_get_contents 显示图像

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

Show image using file_get_contents

phphttp-headersfile-get-contents

提问by Belgin Fish

how can I display an image retrieved using file_get_contents in php?

如何在 php 中显示使用 file_get_contents 检索到的图像?

Do i need to modify the headers and just echo it or something?

我是否需要修改标题并只回显它或其他什么?

Thanks!

谢谢!

采纳答案by Pekka

Do i need to modify the headers and just echo it or something?

我是否需要修改标题并只回显它或其他什么?

exactly.

确切地。

Send a header("content-type: image/your_image_type");and the data afterwards.

发送 aheader("content-type: image/your_image_type");和之后的数据。

回答by robjmills

You can use readfileand output the image headers which you can get from getimagesizelike this:

您可以使用readfile并输出可以从getimagesize获得的图像标题,如下所示:

$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);

The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contentswill read the file into memory which is unnecessary in this content and potentially intensive for large files.

您应该在此处使用 readfile 的原因是它将文件直接输出到输出缓冲区,因为file_get_contents会将文件读入内存,这在此内容中是不必要的,并且对于大文件可能会很密集。

回答by Ya?ar Xavan

$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="' . $src . '">';

回答by Mike Caron

You can do that, or you can use the readfilefunction, which outputs it for you:

您可以这样做,也可以使用readfile为您输出它的函数:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

编辑:Derp,修复了明显明显的错字。

回答by Mochammad Taufiq

you can do like this :

你可以这样做:

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>

回答by darighteous1

Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.

对@seengee 答案的小编辑:为了工作,您需要在变量周围使用花括号,否则您会收到错误消息。

header("Content-type: {$imginfo['mime']}");

header("Content-type: {$imginfo['mime']}");