使用 file_get_contents 显示图像

发布于 2024-10-04 18:21:39 字数 87 浏览 12 评论 0原文

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

我是否需要修改标题并仅回显它或其他内容?

谢谢!

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

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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

南薇 2024-10-11 18:21:39

您可以使用 readfile 并输出可以从 getimagesize 像这样:

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

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

You can use readfile and output the image headers which you can get from getimagesize like this:

$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_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.

小霸王臭丫头 2024-10-11 18:21:39
$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 . '">';
$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 . '">';
筱果果 2024-10-11 18:21:39

我是否需要修改标题并仅回显它或其他内容?

确切地。

发送 header("content-type: image/your_image_type"); 以及随后的数据。

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.

独留℉清风醉 2024-10-11 18:21:39

你可以这样做:

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

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

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);
?>
林空鹿饮溪 2024-10-11 18:21:39

您可以这样做,或者您可以使用 readfile 函数,它会为您输出:

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

编辑:Derp,修复了明显的明显拼写错误。

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

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

Edit: Derp, fixed obvious glaring typo.

咿呀咿呀哟 2024-10-11 18:21:39

我们可以使用文件签名来识别 Mime 类型。 请参阅此内容以了解有关文件签名的更多信息

function getBytesFromHexString($hexdata)
{
    for($count = 0; $count < strlen($hexdata); $count+=2)
        $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
    
    return implode($bytes);
}

function getImageMimeType($imagedata)
{
    $imagemimetypes = [
        "jpeg" => "FFD8", 
        "png" => "89504E470D0A1A0A", 
        "gif" => "474946",
        "bmp" => "424D", 
        "tiff" => "4949",
        "tiff" => "4D4D"
    ];
 
    foreach ($imagemimetypes as $mime => $hexbytes)
    {
        $bytes = getBytesFromHexString($hexbytes);
        if (substr($imagedata, 0, strlen($bytes)) == $bytes)
            return $mime;
    }
  
    return NULL;
}

$uri = "your img url";

if($img = file_get_contents($uri)) {
    echo $mimeType = $this->getImageMimeType($img);
}

了解更多详细信息参见此处

we can identify Mime type using File Signature. refer this for know more about what is file signatures

function getBytesFromHexString($hexdata)
{
    for($count = 0; $count < strlen($hexdata); $count+=2)
        $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
    
    return implode($bytes);
}

function getImageMimeType($imagedata)
{
    $imagemimetypes = [
        "jpeg" => "FFD8", 
        "png" => "89504E470D0A1A0A", 
        "gif" => "474946",
        "bmp" => "424D", 
        "tiff" => "4949",
        "tiff" => "4D4D"
    ];
 
    foreach ($imagemimetypes as $mime => $hexbytes)
    {
        $bytes = getBytesFromHexString($hexbytes);
        if (substr($imagedata, 0, strlen($bytes)) == $bytes)
            return $mime;
    }
  
    return NULL;
}

$uri = "your img url";

if($img = file_get_contents($uri)) {
    echo $mimeType = $this->getImageMimeType($img);
}

for more details see here

暖风昔人 2024-10-11 18:21:39

防止 ddos​​

function view_file($f){
        if(is_file($f)){
            $ext=strtolower(pathinfo($f,PATHINFO_EXTENSION));
            $gambar=array('jpg','jpeg','jpe','jif','jfif','jfi','png','gif','webp','tiff','tif','bmp','dib','heif','heic','jp2','j2k','jpf','jpx','jpm','mj2','svg','svgz');
            $video=array('webm','mpg','mp2','mpeg','mpe','mpv','ogg','mp4','m4p','m4v','avi','avi','mov','qt','flv','swf');
            $audio=array('wav','aif','mp3','mid');
            $t=24;
            $time=time();
            $interval=3600*$t;
            if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
                $modified_time=@$_SERVER['HTTP_IF_MODIFIED_SINCE'];
                if(strtotime($modified_time)+$interval>time()){
                    header("HTTP/1.1 304");
                }
            }
            header('Cache-Control: public');
            header('Last-Modified: '.gmdate('r',$time));
            header('Expires: '.gmdate('r',($time+$interval)));
            header('Cache-Control: max-age='.$interval);
            $c=' style="margin:0;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);">';
            $_64='src="data:'.$ext.';base64,'.base64_encode(file_get_contents($f)).'"';
            if(in_array($ext,$gambar)){
                $s='<div'.$c.'<img '.$_64.'></div>';
            }elseif(in_array($ext,$video)){
                $s='<video style="position:fixed;right:0;bottom:0;min-width:90%;min-height:90%;width:auto;height:auto;z-index:-100;" controls autoplay loop playsinline>'.
                    '<source '.$_64.' type="video/'.$ext.'"></video>';
            }elseif(in_array($ext,$audio)){
                $s='<div'.$c.'<h4>'.$f.'</h4><audio controls autoplay loop><source '.$_64.' type="audio/'.$ext.'"></audio></div>';
            }else{
                setlocale(LC_ALL,'en_US.UTF-8');
                $s='<pre style="line-height:unset;background-color:#fff">'.mb_convert_encoding(highlight_string(file_get_contents($f),1),'ISO-8859-2','UTF-8').'</pre>';
            }
            return(die($s));
        }else{return(false);}
    }

prevent ddos

function view_file($f){
        if(is_file($f)){
            $ext=strtolower(pathinfo($f,PATHINFO_EXTENSION));
            $gambar=array('jpg','jpeg','jpe','jif','jfif','jfi','png','gif','webp','tiff','tif','bmp','dib','heif','heic','jp2','j2k','jpf','jpx','jpm','mj2','svg','svgz');
            $video=array('webm','mpg','mp2','mpeg','mpe','mpv','ogg','mp4','m4p','m4v','avi','avi','mov','qt','flv','swf');
            $audio=array('wav','aif','mp3','mid');
            $t=24;
            $time=time();
            $interval=3600*$t;
            if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
                $modified_time=@$_SERVER['HTTP_IF_MODIFIED_SINCE'];
                if(strtotime($modified_time)+$interval>time()){
                    header("HTTP/1.1 304");
                }
            }
            header('Cache-Control: public');
            header('Last-Modified: '.gmdate('r',$time));
            header('Expires: '.gmdate('r',($time+$interval)));
            header('Cache-Control: max-age='.$interval);
            $c=' style="margin:0;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);">';
            $_64='src="data:'.$ext.';base64,'.base64_encode(file_get_contents($f)).'"';
            if(in_array($ext,$gambar)){
                $s='<div'.$c.'<img '.$_64.'></div>';
            }elseif(in_array($ext,$video)){
                $s='<video style="position:fixed;right:0;bottom:0;min-width:90%;min-height:90%;width:auto;height:auto;z-index:-100;" controls autoplay loop playsinline>'.
                    '<source '.$_64.' type="video/'.$ext.'"></video>';
            }elseif(in_array($ext,$audio)){
                $s='<div'.$c.'<h4>'.$f.'</h4><audio controls autoplay loop><source '.$_64.' type="audio/'.$ext.'"></audio></div>';
            }else{
                setlocale(LC_ALL,'en_US.UTF-8');
                $s='<pre style="line-height:unset;background-color:#fff">'.mb_convert_encoding(highlight_string(file_get_contents($f),1),'ISO-8859-2','UTF-8').'</pre>';
            }
            return(die($s));
        }else{return(false);}
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文