php读取图片内容并输出到浏览器的实现代码

2019-11-16,,,

代码很简单,网上都能找到,但在我机子上就是显示不出来,显示出的一直是这个php文件路径,


费了点时间才搞定,原来是我的<?php这个标签前面有多的空格,删掉就ok了,细节问题,粗心得很,真的很无语。


网上查了下,有这样一说:
如果php以图片,zip,exe等文件输出到浏览器,而前面还输出了其他字符,那就会是你看到的乱码。
应该是输出图片前有输出空格或其他字符造成的,可以检查一下输出图片前有没有其他字符,
如果是utf-8编码记得保存为无BOM的文件。
相关代码如下:
复制代码 代码如下:
class imgdata{
        public $imgsrc;
        public $imgdata;
        public $imgform;
        public function getdir($source){
                $this->imgsrc  = $source;
        }
        public function img2data(){
                $this->_imgfrom($this->imgsrc);
                return $this->imgdata=fread(fopen($this->imgsrc,'rb'),filesize($this->imgsrc));       
        }
        public function data2img(){
                header("content-type:$this->imgform");
                echo $this->imgdata;
                //echo $this->imgform;
                //imagecreatefromstring($this->imgdata);
        }
        public function _imgfrom($imgsrc){
                $info=getimagesize($imgsrc);
                //var_dump($info);
                return $this->imgform = $info['mime'];
        }
}
$n = new imgdata;
$n -> getdir("1.jpg");
$n -> img2data();
$n -> data2img();

《php读取图片内容并输出到浏览器的实现代码.doc》

下载本文的Word格式文档,以方便收藏与打印。