PHP图片转base64

项目场景:

网络图片转base64,,本地图片转base64


    /**
     * @param $img_file
     * @return string\
     * 本地图片转base64
     */
    public function imgToBase64($img_file) {
        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
            }
            fclose($fp);
        }
        return $img_base64; //返回图片的base64
    }

    /**
     * @param $img
     * @return string
     * 网络图片转base64
     */
    public function n_img_base_64($img){
        $imageInfo = getimagesize($img);
        return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
    }

批注:

用于个人总结,菜鸟一枚大佬轻喷,如有问题欢迎指证,如果对大家有帮助那再好不过;


版权声明:本文为qq_43024877原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。