前端压缩图片
场景:
钱包ocr识别照片获取对应的卡号
问题:
H5调起摄像机或相册时,图片过大,网关负载过小,
解决办法:
起初是后台人员加大网关的负载,或者测试的时候使用技术手段将图片压缩一下在上传,由此引发思考。前端是否可以拿到图片时进行等比的压缩并传到后台
html,h5调起摄像头
<input
type="file"
accept="image/*"
ref="upfile"
style="
opacity: 0;
z-index: 1;
position: absolute;
right: 43px;
width: 24px;
"
@change="fileUpload"
/>
获取图片及检测图片
fileUpload() {
let file = this.$refs.upfile;
let fileName = file.value;
let files = file.files;
console.log(files[0], fileName, file.raw);
if (fileName == null || fileName == "") {
alert("请选择文件");
} else {
let fileType = fileName.slice(-4, fileName.length);
console.log(fileType);
if (fileType == ".jpg" || fileType == ".png" || fileType == "jpeg") {
if (files[0]) {
var maxWidth = 500;
var maxHeight = 700;
var quality = 0.92;
// this.uploadImgToBase64(files[0]).then((res) => {
this.compressImage(files[0], maxWidth, maxHeight, quality).then(
(res) => {
console.log("res", res);
let baseimg = res.result.split("base64,")[1];
console.log(baseimg);
// let baseimg = res;
let data = {
cardImg: baseimg,
};
BankCardOcr(data).then((res) => {
console.log(res, "ocr");
if (res.retCode == "0000") {
// 上传代码返回结果之后
this.instBankName = res.bankName;
this.acctNo = res.acctNo;
this.halfacctNo = res.acctNo;
} else {
Toast(res.retMsg);
}
});
}
);
} else {
alert("请选择要上传的图片");
}
} else {
alert("上传文件类型错误!");
}
}
},
js压缩图片
// 压缩图片
compressImage(file, maxWidth, maxHeight, quality) {
let that = this;
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const img = new Image();
img.src = event.target.result;
img.onload = function () {
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(
function (blob) {
that
.blobTo64(blob)
.then((text) => {
resolve(text);
})
.catch((error) => {
reject(error);
});
},
file.type,
quality
);
};
};
reader.onerror = function (error) {
reject(error);
};
});
},
将图片格式转化为base64格式
blobTo64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function () {
// 图片转base64完成后返回reader对象
resolve(reader);
};
reader.onerror = reject;
});
},
本文作者:张尊娟
本文链接:https://www.cnblogs.com/wszzj/p/17545999.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步