前端代碼
function readFile(obj){
var file = obj.files[0];
//判斷類型是不是圖片
if(!/image\/\w+/.test(file.type)){
alert("請確保文件爲圖像類型");
return false;
}
var objUrl = getObjectURL(file) ; //獲取圖片的路徑,該路徑不是圖片在本地的路徑
if (objUrl) {
$(".simg").css("display","inline-block");
$(".simg img").eq(0).attr("src", objUrl) ; //將圖片路徑存入src中,顯示出圖片
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
dealImage(this.result,{width:260},function(base){
var data={
'image':base
};
post("{:url('api/upload/base64')}",data,callpay,'','','');
function callpay(res){
}
});
}
}
/**
* 圖片壓縮,默認同比例壓縮
* @param {Object} path
* pc端傳入的路徑可以爲相對路徑,但是在移動端上必須傳入的路徑是照相圖片儲存的絕對路徑
* @param {Object} obj
* obj 對象 有 width, height, quality(0-1)
* @param {Object} callback
* 回調函數有一個參數,base64的字符串數據
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默認按比例壓縮
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默認圖片質量爲0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 創建屬性節點
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 圖像質量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所繪製出的圖像越模糊
// var base64 = canvas.toDataURL('image/jpeg', quality );
var base64 = canvas.toDataURL('image/gif', quality );
// 回調函數返回base64的值
callback(base64);
}
}
php 接收base64
public function base64(Request $request){
$param = $request->param();
//目錄的upload文件夾下
$up_dir = "./static/uploads/".date('Ymd', time()) . "/"; //創建目錄
if(!file_exists($up_dir)){
mkdir($up_dir,0777,true);
}
$base64_img = trim($param['image']);
if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
$type = $result[2];
if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
$new_file = $up_dir.time().'.'.$type;
if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
$img_path = str_replace('../../..', '', $new_file);
$data=[
'url' =>str_replace("./static/uploads",'',$img_path),
'created_at' => time()
];
$image=Db::name('images')->insert($data);
$img_id=Db::name('images')->getLastInsID();
return Json([
'code'=>1,
'msg' =>'上傳圖片成功',
'data'=>[
'img_id'=>$img_id,
'url' =>getImgUrlById($img_id)
]
]);
}else{
return Json([
'code'=>0,
'msg'=>"上傳圖片失敗,請稍後重試"
]);
}
}else{
//文件類型錯誤
return Json([
'code'=>0,
'msg'=>'圖片上傳類型錯誤'
]);
}
}
}