php读取文件转换base64 格式
测试附录地址:http://imgbase64.duoshitong.com/
代码示例:
//读取图片文件,转换成base64编码格式 $image_file = '4296762_165319032930_2.jpg'; $image_info = @getimagesize($image_file); $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file)));
接收图片base64内容转换成图片文件
$base64_image_content = isset($_REQUEST['image_content']) ? trim($_REQUEST['image_content']) : ''; if(empty($base64_image_content)){ ajax_return(0,'图片内容不能为空'); } try{ //匹配出图片的格式 $image_patern = '/^(data:\s*image\/(\w+);base64,)/'; if (preg_match($image_patern, $base64_image_content, $result)) { $type = $result[2]; //检测格式 $allow_extension = ['jpg','jpeg','gif','png','bmp']; if(!in_array($result[1],$allow_extension)){ ajax_return(0,'仅允许jpg/jpeg/gif/png/bmp格式的图片上传'); } $new_file = "./" . time() . ".{$type}"; $file_content = base64_decode(str_replace($result[1], '', $base64_image_content)); file_put_contents($new_file, $file_content); } else{ ajax_return(0,'图片内容格式错误'); } } catch(Exception $e){ ajax_return(0,'图片保存异常:'.$e->getMessage()); }
转载请注明:苏demo的别样人生 » php 读取图片转换base64 上传