让所有浏览器轻松预览web格式图片包括webp图片,jpeg图片,png图片,gif图片等

让所有浏览器轻松预览web格式图片包括webp图片,jpeg图片,png图片,gif图片等

具体需要服务端那边做下转化,php版本代码如下:

<?php
class imagedata{
    public $imgsrc;
    public $imgdata;
    public $imgform;
    public function getsrc($source){
        $this->imgsrc = $source;
    }
    public function img2data(){
        
        if(file_exists($this->imgsrc)) {
            $this->imgdata = fread(fopen($this->imgsrc,'rb'),filesize($this->imgsrc));
        } else {
            if(strpos($this->imgsrc,"://")) {
                $this->imgdata = file_get_contents($this->imgsrc);
            } else {
                $checkfile = $_SERVER["DOCUMENT_ROOT"].'/'.ltrim($this->imgsrc,'/');
                if(file_exists($checkfile)) {
                    $this->imgsrc = $checkfile;
                    $this->imgdata = fread(fopen($checkfile,'rb'),filesize($checkfile));
                } else {
                    $http_protocol = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https:' : 'http:';
                    $checkurl = $http_protocol.'//'.$_SERVER["HTTP_HOST"].'/'.ltrim($this->imgsrc,'/');
                    $this->imgsrc = $checkurl;
                    $this->imgdata = file_get_contents($this->imgsrc);
                }
            }
        }
        $this->_imgfrom($this->imgsrc);
        ////# imagecreatefromstring($this->imgdata);
        return $this->imgdata;
    }
    public function data2img(){
        $this->img2data();
        if($this->imgform == 'image/webp') {
            $this->webp2jpeg($this->imgsrc);
        }
        else {
            header("content-type:$this->imgform");
            echo $this->imgdata;
        }
    }
    public function _imgfrom($imgsrc){
        $info = getimagesize($imgsrc);
        return $this->imgform = $info['mime'];
    }
    public function webp2jpeg($source) {
        header("content-type:image/jpeg");
        $source_image = imagecreatefromwebp($source);
        imagejpeg($source_image, null, 100);
        imagedestroy($source_image);
    }
}

$file = $_GET["file"];
if(!empty($file)) {
    $imgdata = new imagedata;
    $imgdata->getsrc($file);
    $imgdata->data2img();
}

//轻松预览web格式图片包括webp图片,jpeg图片,png图片,gif图片等
//.e.g. /imagedata.php?file=newfile1.webp
//.e.g. /imagedata.php?file=test.jpg
?>

 

posted @ 2023-06-14 16:47  php学习笔记  阅读(221)  评论(0编辑  收藏  举报