一.引入layui 上傳插件
layui.use('upload', function(){
var upload = layui.upload;
var uploadInst = upload.render({
elem: '#uploadImg' //觸發(fā)事件元素
,url: url// 這里的請(qǐng)求沒啥作用,我只是不想讓它報(bào)接口異常提示,寫的臨時(shí)接口(不做處理的)
,exts:"jpg|png|jpeg"
,accept:"images"
,size:"10240"
,before: function(obj){
//預(yù)讀本地文件示例,不支持ie8
obj.preview(function(index, file, result){
//$(demo).attr('src', result); //圖片鏈接(base64)
demo=$('#imgBox');
imgBase64(demo,file,2,0,result,function (base64) {
$('#license').val(base64)
var data = {
idcard: '',
eno: '',
base64: base64,
index: 0
}
});
});
}
,done: function(res){
//上傳成功
}
,error: function(){
}
});
})
二.將文件轉(zhuǎn)換成base64 并壓縮圖片大小
function imgBase64(demo,file,wh,mark,bs,callback){
if((file.size+"").length > 6){
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function(e) {
var image = new Image() //新建一個(gè)img標(biāo)簽(還沒嵌入DOM節(jié)點(diǎn))
image.src = e.target.result
image.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var imageWidth = image.width / wh; //壓縮后圖片的大小
var imageHeight = image.height / wh;
canvas.width = imageWidth
canvas.height = imageHeight
context.drawImage(image, 0, 0, imageWidth, imageHeight)
var base64 = canvas.toDataURL('image/jpeg',0.5);// 圖片質(zhì)量0.5
//壓縮完成
$(demo).attr('src', base64);
var data = base64.replace(/^data:image\/\w+;base64,/, "");
var bytes = window.atob(data);
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for(var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
var blob = new Blob([ab], {
type: 'image/jpeg'
});
console.log('壓縮后的圖片大小', blob.size);
if((blob.size+"").length > 6 && mark != 1){ // 超過1MB重新按比例3壓縮一遍
imgBase64(demo,file,3,1,function (res) {
callback(res)
})
}else{
callback(data)
}
}
}
}else{
$(demo).attr('src', bs);
callback(bs.replace(/^data:image\/\w+;base64,/, ""))
}
}
效果如圖:
提交后:
圖片將以base64編碼提交到后臺(tái):
三、在后臺(tái)我們可以將base64圖片轉(zhuǎn)換成圖片
/**bs64 轉(zhuǎn)圖片 */
function base64($base64,$username){
$imageName =$username.'.png';//圖片名稱
$path = "/Uploads/partner/";//圖片路徑
$dir= ? '../'. :'.'.;
if (!is_dir($dir.$path)){ //判斷目錄是否存在 不存在就創(chuàng)建
mkdir($dir.$path,0777,true);
}
$imageSrc= $path."/". $imageName;
//dump($dir.$imageSrc);exit;
if (file_put_contents($dir.$imageSrc, base64_decode($base64))){
//dump( $imageSrc);
$oss= new Service\Upload();
if(file_exists($dir.$imageSrc)){
$content = file_get_contents($dir.$imageSrc);
$error=$oss->uploadImage('member/partner/'.$imageName, $content);//上傳到阿里云oss
$url='阿里云oss url'. $imageName;//返回存儲(chǔ)在阿里云oss的地址
unlink($dir.$imageSrc);//刪除本地圖片
}
return $url;
}
}
或者不轉(zhuǎn)換成圖片直接數(shù)據(jù)庫中保存base64編碼 當(dāng)時(shí)復(fù)雜的圖片base64的編碼很長,數(shù)據(jù)庫字段長度要足夠大
四、在html img 中顯示base64圖片
如沒特殊注明,文章均為方維網(wǎng)絡(luò)原創(chuàng),轉(zhuǎn)載請(qǐng)注明來自http://m.oulysa.com/news/6568.html