图片转base64方法方法汇总

jQuery图片转base64方法

引入fileReader插件filereader.min.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
that.$upload.find('#uploadFile').on('change', function (e) {
var
file = this.files[0],
fileReader = new FileReader();
if(typeof file === 'undefined') {
return false;
}
if(file.type && !/image\/\w+/.test(file.type)) {
alert('请上传图片文件');
return false;
}
fileReader.readAsDataURL(file);
fileReader.onload = function() {
var result = this.result;
var img = new Image();
var exif;
var base64 = result.replace(/^.*?,/, '');
var binary = atob(base64);
var binaryData = new BinaryFile(binary);
exif = EXIF.readFromBinaryFile(binaryData);
var orientation = exif ? exif.Orientation : 1;
cutCanvas.style.display = 'block';
ctrlLayer.style.display = 'block';
that.$upload.find('.upload-info').hide();
that.$upload.find('.review').show();
that.$upload.find('.cut-tips').show();
img.onload = function() {
cutCanvas.getContext("2d").setTransform(1, 0, 0, 1, 0, 0);
var gesturableImg = new ImgTouchCanvas({
canvas: cutCanvas,
contrler: ctrlLayer,
path: img.src,
imgRoate: orientation
});
};
that.isUpload = true;
img.src = result;
};
})

微信小程序图片转base64方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 上传头像
uploadImg() {
let that = this
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success (res) {
wx.showLoading({
title: '上传中…', // 提示的内容,
mask: true // 显示透明蒙层,防止触摸穿透,
})
// tempFilePath可以作为img标签的src属性显示图片
wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[0], // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: r1 => { // 成功的回调
// console.log('data:image/png;base64,' + r1.data)
that.headerUrl = 'data:image/png;base64,' + r1.data
let params = {
code: that.headerUrl
}
that.uploadImg(params)
that.$apply()
},
fail: res => {
wx.hideLoading()
wx.showToast({
title: '上传图片失败',
icon: 'none'
})
}
})
}
})
},