PHP有内置的base64_encode与base64_decode负责进行Base64编码与解码。

一.图片base64编码
只要将图片流读取到,而后使用base64_encode进行进行编码然后拼接上前缀(data:image/png;base64,)即可。

* 图片base64编码 * @param string $img * @param bool $imgHtmlCode * author 江南极客 * @return string function imgBase64Encode($img = '', $imgHtmlCode = true) //如果是本地文件 if(strpos($img,'http') === false && !file_exists($img)){ return $img; //获取文件内容 $file_content = file_get_contents($img); if($file_content === false){ return $img; $imageInfo = getimagesize($img); $prefiex = ''; if($imgHtmlCode){ $prefiex = 'data:' . $imageInfo['mime'] . ';base64,'; $base64 = $prefiex.chunk_split(base64_encode($file_content)); return $base64;

二.图片base64解码
而解码就相对麻烦一点,因为在对图片进行base64编码的时候会加入前缀字符串,编码内会加入这些字符(data:image/png;base64,) ,解码之前需要先去掉这一串字符。

* 片base64解码 * @param string $base64_image_content 图片文件流 * @param bool $save_img 是否保存图片 * @param string $path 文件保存路径 * author 江南极客 * @return bool|string function imgBase64Decode($base64_image_content = '',$save_img = false,$path=''){ if(empty($base64_image_content)){ return false; //匹配出图片的信息 $match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result); if(!$match){ return false; //解码图片内容(方法一) /*$base64_image = preg_split("/(,|;)/",$base64_image_content); $file_content = base64_decode($base64_image[2]); $file_type = substr(strrchr($base64_image[0],'/'),1);*/ //解码图片内容(方法二) $base64_image = str_replace($result[1], '', $base64_image_content); $file_content = base64_decode($base64_image); $file_type = $result[2]; //如果不保存文件,直接返回图片内容 if(!$save_img){ return $file_content; //如果没指定目录,则保存在当前目录下 if(empty($path)){ $path = __DIR__; $file_path = $path."/".date('Ymd',time())."/"; if(!is_dir($file_path)){ //检查是否有该文件夹,如果没有就创建 mkdir($file_path,0777,true); $file_name = time().".{$file_type}"; $new_file = $file_path.$file_name; if(file_exists($new_file)){ //有同名文件删除 @unlink($new_file); if (file_put_contents($new_file, $file_content)){ return $new_file; return false; 1 /*首先要确定 图片 的类型,需要安装一个 php 拓展 php _fileinfo 2 如已安装可以在extension_dir目录下找到 php _fileinfo.dll(windows),fileinfo.so(linux) 3 打开 php .ini,把extension= php _fileinfo.dll前的";"去掉,然后重启ap... /* 图片 转换为 base64 格式 编码 */ $img = 'uploads/01.png'; $ base64 _img = base64 EncodeImage($img); echo ''; function base64 EncodeImage ($image_file) { $ base64 _image = ''; $image_info = geti
PHP 函数源码 function imgTo Base64 ($img_file) { img base64 =′′;if(fileexists(img_ base64 = ''; if (file_exists(imgb​ase64=′′;if(filee​xists(img_file)) { $app_img_file = $img_file; // 图片 的路径 imginfo=getimage...
header('content-type:text/html;charset=utf8');  /*** 图片 上传*/     $str=file_get_contents('C:\Users\lenove\Desktop\1.jpg');     $a= base64 _encode($str);     echo"查看";