记录一下
第一步:
应用 input, capture=”camera” 调用原生相机
<input onchange="photoChange(event)" type="file" accept="image/*" capture="camera" id="upload_file" />
第二步:获取到图片信息
应用 FileReader 读取到图片的信息
function photoChange(el) {
const _this = this;
var file = el.target.files[0];// name: "dangqi1.png" || type: "image/png"
_this.fileName = file.name;
var type = file.type.split('/')[0];
if (type === 'image') {var reader = new FileReader(); // FileReader
reader.readAsDataURL(file);
reader.onloadend = function () {
var dataURL = reader.result;
// 压缩图片
_this.compressImg(dataURL, {
quality: 0.92, // 为了保留图片品质,压缩值设置为 0.92
width: 1000 // 把图片尺寸调整为宽为 1000 的,高度自适应
}, file);
};
} else {alert('上传了非图片');
}
}
第三步:通过 canvas 进行图片解决
// 压缩
function compressImg(path, objCompressed, file) {
var _this = this;
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认压缩后图片规格
var quality = 0.5;
var w = that.width;
var h = that.height;
var scale = w / h;
// 理论要求
w = objCompressed.width || w;
h = objCompressed.height || (w / scale);
if (objCompressed.quality && objCompressed.quality > 0 && objCompressed.quality <= 1) {quality = objCompressed.quality;}
// 生成 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);
// 此处的 base64 就是新失去的压缩图片了,能够用来传输了
var base64 = canvas.toDataURL('image/jpeg', quality);
}
}