<?php header('Content-type:text/html;charset=utf-8'); //讀取圖片文件,轉換成base64編碼格式 $image_file = './face_21.png'; $image_info = getimagesize($image_file); $base64_image_content = "data:{$image_info['mime']};base64," . chunk_split(base64_encode(file_get_contents($image_file))); //保存base64字符串為圖片 //匹配出圖片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = "./test.{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ echo '新文件保存成功:', $new_file; } } ?> <img src="<?php echo $base64_image_content;?>" />
實例:
<html> <head> <meta charset="utf-8"> </head> <body> <img id="articleImg" width="180" height="100"> <input type="file" value="上傳" id="articleImgBtn" /> <script type="text/javascript" src = 'jquery-1.6.2+fix-9521.js'></script> <script type="text/javascript"> $('#articleImgBtn').change(function () { run(this, function (data) { uploadImage(data); }); }); function run(input_file, get_data) { /*input_file:文件按鈕對象*/ /*get_data: 轉換成功后執行的方法*/ if (typeof (FileReader) === 'undefined') { alert("抱歉,你的瀏覽器不支持 FileReader,不能將圖片轉換為Base64,請使用現代瀏覽器操作!"); } else { try { /*圖片轉Base64 核心代碼*/ var file = input_file.files[0]; //這里我們判斷下類型如果不是圖片就返回 去掉就可以上傳任意文件 if (!/image\/\w+/.test(file.type)) { alert("請確保文件為圖像類型"); return false; } var reader = new FileReader(); reader.onload = function () { get_data(this.result); } reader.readAsDataURL(file); } catch (e) { alert('圖片轉Base64出錯啦!' + e.toString()) } } } function uploadImage(img) { //判斷是否有選擇上傳文件 var imgPath = $("#articleImgBtn").val(); if (imgPath == "") { alert("請選擇上傳圖片!"); return; } //判斷上傳文件的后綴名 var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1); if (strExtension != 'jpg' && strExtension != 'gif' && strExtension != 'png' && strExtension != 'bmp') { alert("請選擇圖片文件"); return; } $.ajax({ type: "POST", url: 'signup.php?act=reg', //jsonp跨域,但不支持POST請求 // data: {file: img.substr(img.indexOf(',') + 1)}, //視情況將base64的前面字符串data:image/png;base64,刪除 data: {file: img}, //視情況將base64的前面字符串data:image/png;base64,刪除 cache: false, success: function (data) { var return_info = JSON.parse(data); if (return_info.status) { $("#articleImg").attr('src', return_info.path); alert("上傳成功"); } else { alert(return_infoerr_info); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("上傳失敗,請檢查網絡后重試"); } }); } </script> </body> </html>
function upload_image($file_data){ $upload_result = array('status' => true, 'msg'=>'','err_info'=>''); if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file_data, $result)) { //處理base64字符串 $img_base64 = str_replace($result[1], '', $file_data); $img_base64 = str_replace('=', '', $img_base64); $source_img = base64_decode($img_base64); //判斷文件大小 $file_size = //上傳目錄 $basedir = './img_test'; //后綴 $img_suffix = $result[2];//文件后綴 //文件名 // $filename = uniqid();//文件名 $filename = date('YmdHis',time());//文件名 //文件完整路徑 $filepath = $basedir . "/" . $filename . "." . $img_suffix; //目錄若果不存在,則創建目錄 if(!is_dir($basedir)){ mkdir($basedir); chmod($basedir,0777); } //上傳文件 try { file_put_contents($filepath, $img_base64); $filepath = substr($filepath, 1); $upload_result = array('status' => true, 'msg'=>'上傳成功','err_info'=>'','path'=>$filepath); return $upload_result; } catch (Exception $e) { $upload_result = array('status' => false, 'msg'=>'上傳失敗','err_info'=>$e->getMessage()); return $upload_result; } // if (file_put_contents($filepath, base64_decode(str_replace($result[1], '', $file_data)))) { // //$size = getimagesize($filepath); // $filepath = substr($filepath, 1); // //$arr['filepath'] = $filepath; // //$arr['size'] = $size[3]; // return $filepath; // }else{ // return false; // } }else{ $upload_result = array('status' => false, 'msg'=>'上傳失敗','err_info'=>'請攜帶base64字符串的前綴'); return $upload_result; } } $res = upload_image($file_data); echo json_encode($res);