增加压缩图片

This commit is contained in:
qijq 2025-06-26 02:09:26 +08:00
parent f54aacadfc
commit 1f763ac279
8 changed files with 388 additions and 499 deletions

View File

@ -10,18 +10,18 @@
* @seehttps://mall.gpxscs.cn/mobile/shop/oss/upload
*/
import http from '../utils/http'
import config from '../config/config'
import http from "../utils/http";
import config from "../config/config";
export function UploadFilePromise(filePath, formData) {
let ukey = uni.getStorageSync('ukey');
let ukey = uni.getStorageSync("ukey");
return new Promise((resolve, reject) => {
uni.uploadFile({
// 完整上传路径 H5端需要解决跨域问题
url: 'https://mall.gpxscs.cn/mobile/shop/oss/upload',
method: 'POST',
url: "https://mall.gpxscs.cn/mobile/shop/oss/upload",
method: "POST",
filePath: filePath,
name: 'upfile',
name: "upfile",
formData: { perm_key: ukey, ...formData },
success: (res) => {
const result = JSON.parse(res.data);
@ -34,36 +34,35 @@ export function UploadFilePromise(filePath, formData) {
});
}
export function batchNoApi (filePath, file, type){
return new Promise((resolve, reject) => {
export function batchNoApi(filePath, file, type) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url:'https://mall.gpxscs.cn/mobile/shop/lakala/tk/uploadOcrImg',
url: "https://mall.gpxscs.cn/mobile/shop/lakala/tk/uploadOcrImg",
method: "POST",
filePath,
name:'upfile',
formData: {
name: "upfile",
formData: {
imgType: type,
},
success: (res) =>{
if(res?.data){
resolve(JSON.parse(res?.data)?.data)
},
success: (res) => {
if (res?.data) {
resolve(JSON.parse(res?.data)?.data);
}
},
fail: (res) =>{
reject(res)
}
})
})
fail: (res) => {
reject(res);
},
});
});
}
export function imgOcrResultApi (data){
return http({
url:'/shop/lakala/tk/imgOcrResult',
method:'POST',
export function imgOcrResultApi(data) {
return http({
url: "/shop/lakala/tk/imgOcrResult",
method: "POST",
headers: {
'content-type': 'application/x-www-form-urlencoded',
"content-type": "application/x-www-form-urlencoded",
},
data,
})
});
}

View File

@ -1,173 +1,177 @@
{
"name" : "小发同城商家版",
"appid" : "__UNI__95F809F",
"package" : "com.xiaofa.shopAdmin",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : 102,
"transformPx" : false,
/* 5+App */
"app-plus" : {
"usingComponents" : true,
"nvueStyleCompiler" : "uni-app",
"compilerVersion" : 3,
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
"name": "小发同城商家版",
"appid": "__UNI__95F809F",
"package": "com.xiaofa.shopAdmin",
"description": "",
"versionName": "1.0.0",
"versionCode": 102,
"transformPx": false,
/* 5+App */
"app-plus": {
"usingComponents": true,
"nvueStyleCompiler": "uni-app",
"compilerVersion": 3,
"splashscreen": {
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
},
"ios": {
"capabilities": {
"com.apple.SafariKeychain": true
}
},
/* */
"modules": {
"Maps": {},
"Camera": {},
"Record": {},
"VideoPlayer": {},
"UIWebview": {},
"Push": {}
},
/* */
"distribute": {
/* android */
"android": {
"permissions": [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios */
"ios": {
"privacyDescription": {
"NSPhotoLibraryAddUsageDescription": "此App会在上传头像图片服务中访问您的相机权限",
"NSPhotoLibraryUsageDescription": "此App会在上传头像图片服务中访问您的相机权限",
"NSCameraUsageDescription": "此App会在上传头像图片服务中访问您的相机权限",
"NSMicrophoneUsageDescription": "此APP会在使用声音识别服务中使用您的麦克风权限",
"NSLocationWhenInUseUsageDescription": "此App会在使用导航服务中使用您的定位权限",
"NSLocationAlwaysUsageDescription": "此App会在使用导航服务中使用您的定位权限",
"NSLocationAlwaysAndWhenInUseUsageDescription": "此App会在使用导航服务中使用您的定位权限"
},
/* */
"modules" : {
"Maps" : {},
"Camera" : {},
"Record" : {},
"VideoPlayer" : {},
"UIWebview" : {},
"Push" : {}
},
/* */
"distribute" : {
/* android */
"android" : {
"permissions" : [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
]
},
/* ios */
"ios" : {
"privacyDescription" : {
"NSPhotoLibraryAddUsageDescription" : "此App会在上传头像图片服务中访问您的相机权限",
"NSPhotoLibraryUsageDescription" : "此App会在上传头像图片服务中访问您的相机权限",
"NSCameraUsageDescription" : "此App会在上传头像图片服务中访问您的相机权限",
"NSMicrophoneUsageDescription" : "此APP会在使用声音识别服务中使用您的麦克风权限",
"NSLocationWhenInUseUsageDescription" : "此App会在使用导航服务中使用您的定位权限",
"NSLocationAlwaysUsageDescription" : "此App会在使用导航服务中使用您的定位权限",
"NSLocationAlwaysAndWhenInUseUsageDescription" : "此App会在使用导航服务中使用您的定位权限"
},
"dSYMs" : false
},
/* SDK */
"sdkConfigs" : {
"maps" : {},
"push" : {
"igexin" : {
"appid" : "KXgzOaKSzd5HG3p9IPaVa8",
"appkey" : "neXXX9r1Tc7gMxN2PIcHA1",
"appsecret" : "aQQys9eufd8KHH1Y0kfQm6"
},
"unipush" : {
"version" : "2",
"offline" : true,
"hms" : {},
"oppo" : {},
"vivo" : {},
"mi" : {},
"meizu" : {},
"honor" : {},
"fcm" : {}
}
}
},
"icons" : {
"android" : {
"hdpi" : "unpackage/res/icons/72x72.png",
"xhdpi" : "unpackage/res/icons/96x96.png",
"xxhdpi" : "unpackage/res/icons/144x144.png",
"xxxhdpi" : "unpackage/res/icons/192x192.png"
},
"ios" : {
"appstore" : "unpackage/res/icons/1024x1024.png",
"ipad" : {
"app" : "unpackage/res/icons/76x76.png",
"app@2x" : "unpackage/res/icons/152x152.png",
"notification" : "unpackage/res/icons/20x20.png",
"notification@2x" : "unpackage/res/icons/40x40.png",
"proapp@2x" : "unpackage/res/icons/167x167.png",
"settings" : "unpackage/res/icons/29x29.png",
"settings@2x" : "unpackage/res/icons/58x58.png",
"spotlight" : "unpackage/res/icons/40x40.png",
"spotlight@2x" : "unpackage/res/icons/80x80.png"
},
"iphone" : {
"app@2x" : "unpackage/res/icons/120x120.png",
"app@3x" : "unpackage/res/icons/180x180.png",
"notification@2x" : "unpackage/res/icons/40x40.png",
"notification@3x" : "unpackage/res/icons/60x60.png",
"settings@2x" : "unpackage/res/icons/58x58.png",
"settings@3x" : "unpackage/res/icons/87x87.png",
"spotlight@2x" : "unpackage/res/icons/80x80.png",
"spotlight@3x" : "unpackage/res/icons/120x120.png"
}
}
},
"splashscreen" : {
"androidStyle" : "common"
}
"dSYMs": false
},
/* SDK */
"sdkConfigs": {
"maps": {},
"push": {
"igexin": {
"appid": "KXgzOaKSzd5HG3p9IPaVa8",
"appkey": "neXXX9r1Tc7gMxN2PIcHA1",
"appsecret": "aQQys9eufd8KHH1Y0kfQm6"
},
"unipush": {
"version": "2",
"offline": true,
"hms": {},
"oppo": {},
"vivo": {},
"mi": {},
"meizu": {},
"honor": {},
"fcm": {}
}
}
},
/* */
"quickapp" : {},
/* */
"mp-weixin" : {
"appid" : "",
"setting" : {
"urlCheck" : false
},
"icons": {
"android": {
"hdpi": "unpackage/res/icons/72x72.png",
"xhdpi": "unpackage/res/icons/96x96.png",
"xxhdpi": "unpackage/res/icons/144x144.png",
"xxxhdpi": "unpackage/res/icons/192x192.png"
},
"usingComponents" : true
},
"h5" : {
// "devServer" : {
// "https" : true,
// "host" : "127.0.0.1",
// "port" : 8080,
// "disableHostCheck" : true,
// "proxy" : {
// "/place/v2/suggestion" : {
// "target" : "https://api.map.baidu.com",
// "changeOrigin" : true,
// "secure" : false
// },
// "/admin/shop/shop-base-product-category/list" : {
// "target" : "https://mall.gpxscs.cn",
// "changeOrigin" : true
// }
// }
// },
"title" : "小发商城商家中心",
"template" : "index.html",
"router" : {
"mode" : "history",
"base" : "/mchapp/"
"ios": {
"appstore": "unpackage/res/icons/1024x1024.png",
"ipad": {
"app": "unpackage/res/icons/76x76.png",
"app@2x": "unpackage/res/icons/152x152.png",
"notification": "unpackage/res/icons/20x20.png",
"notification@2x": "unpackage/res/icons/40x40.png",
"proapp@2x": "unpackage/res/icons/167x167.png",
"settings": "unpackage/res/icons/29x29.png",
"settings@2x": "unpackage/res/icons/58x58.png",
"spotlight": "unpackage/res/icons/40x40.png",
"spotlight@2x": "unpackage/res/icons/80x80.png"
},
"iphone": {
"app@2x": "unpackage/res/icons/120x120.png",
"app@3x": "unpackage/res/icons/180x180.png",
"notification@2x": "unpackage/res/icons/40x40.png",
"notification@3x": "unpackage/res/icons/60x60.png",
"settings@2x": "unpackage/res/icons/58x58.png",
"settings@3x": "unpackage/res/icons/87x87.png",
"spotlight@2x": "unpackage/res/icons/80x80.png",
"spotlight@3x": "unpackage/res/icons/120x120.png"
}
}
},
"splashscreen": {
"androidStyle": "common"
}
}
},
/* */
"quickapp": {},
/* */
"mp-weixin": {
"appid": "",
"setting": {
"urlCheck": false
},
"mp-alipay" : {
"usingComponents" : true
},
"mp-baidu" : {
"usingComponents" : true
},
"mp-toutiao" : {
"usingComponents" : true
},
"uniStatistics" : {
"enable" : false
},
"vueVersion" : "2"
"usingComponents": true
},
"h5": {
// "devServer" : {
// "https" : true,
// "host" : "127.0.0.1",
// "port" : 8080,
// "disableHostCheck" : true,
// "proxy" : {
// "/place/v2/suggestion" : {
// "target" : "https://api.map.baidu.com",
// "changeOrigin" : true,
// "secure" : false
// },
// "/admin/shop/shop-base-product-category/list" : {
// "target" : "https://mall.gpxscs.cn",
// "changeOrigin" : true
// }
// }
// },
"title": "小发商城商家中心",
"template": "index.html",
"router": {
"mode": "history",
"base": "/mchapp/"
}
},
"mp-alipay": {
"usingComponents": true
},
"mp-baidu": {
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"vueVersion": "2"
}
/* 5+App */

View File

@ -455,6 +455,13 @@
@cancel="showEndTime = false"
></u-datetime-picker>
<u-toast ref="uToast" />
<u-loading-page
:loading="loading"
bgColor="rgba(0,0,0,0.5)"
fontSize="32rpx"
color="#fff"
loadingText="数据正在加载中..."
></u-loading-page>
</view>
</template>
@ -468,8 +475,7 @@ import {
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
import tuiRadio from "@/components/tui-radio/tui-radio.vue";
import tuiRadioGroup from "@/components/tui-radio-group/tui-radio-group.vue";
import { compressImg } from '@/utils/tool.js'
import { H5compressImg, getBase64Size } from "@/utils/tool.js";
const orcImgTypeConf = {
FR_ID_CARD_FRONT: "FR_ID_CARD_FRONT",
@ -493,6 +499,7 @@ export default {
showPicker: false,
showStartTime: false,
showEndTime: false,
loading: false,
startTime: null,
endTime: null,
startMinDate: 0,
@ -549,9 +556,9 @@ export default {
license_type_name: "",
orcTimeout: null,
action: "",
limitType: ['png', 'jpg', 'jpeg'], //
limitType: ["png", "jpg", "jpeg"], //
fileMaxSize: 1 * 1024 * 1024, // 1M
maxSize:5 * 1024 * 1024, //20M
maxSize: 5 * 1024 * 1024, //20M
fileMinSize: 5 * 1024, // 5KB
fileList: [],
fileList2: [],
@ -716,50 +723,47 @@ export default {
uni.navigateBack();
},
overSize(e) {
uni.$u.toast("上传图片大小不能超过8MB!");
uni.$u.toast("上传图片大小不能超过5MB!");
},
compressImage(url) {
return new Promise((reslove, reject) => {
const tempFilePath = url //url
uni.compressImage({
const tempFilePath = url; //url
uni.compressImage({
src: tempFilePath,
quality: 90, //
quality: 75, //
success: (res) => {
reslove(res.tempFilePath) //
reslove(res.tempFilePath); //
},
fail: (error) => {
console.log('压缩失败', error)
}
})
})
},
async handerCompressImg(source, compressionRatio) {
let that = this;
return new Promise((resolve, reject) => {
compressImg(source.url, compressionRatio, source.type, compressRes => {
resolve(compressRes);
})
}).then((res) => {
source.size = res.size
// window.URL.revokeObjectURL(source.url) // ,
source.url = res.source
source.thumb = res.source
return source
}).catch(err => {
console.log('图片压缩失败', err)
})
console.log("压缩失败", error);
},
});
});
},
async getOcrText(filePath, file, type) {
return new Promise(async (resolve, reject) => {
this.loading = true;
//#ifdef APP-PLUS
filePath = await this.compressImage(filePath);
filePath = await this.compressImage(filePath);
//#endif
// base64
//#ifdef H5
filePath = await H5compressImg(filePath, 0.75);
//#endif
let size = getBase64Size(filePath);
console.log(size);
const batchNoRes = await batchNoApi(filePath, file, type);
const batchNo = batchNoRes.batchNo;
if (!batchNoRes) {
this.loading = false;
reject(batchNoRes);
}
const formData = new FormData();
let formDataStr = "";
@ -778,131 +782,70 @@ export default {
});
const imgOcrRes = await imgOcrResultApi(formDataStr);
if (imgOcrRes.status == 250) {
switch (type) {
case "FR_ID_CARD_FRONT":
uni.showToast({
title: "上传身份证正面图片错误,请重新上传",
icon: "error",
duration: 2000,
});
this.form.legal_person_id_images == "";
this.fileList3 = [];
break;
case "FR_ID_CARD_BEHIND":
uni.showToast({
title: "上传身份证反面图片错误,请重新上传",
icon: "error",
duration: 2000,
});
this.form.legal_person_id_images2 == "";
this.fileList4 = [];
break;
case "ID_CARD_FRONT":
uni.showToast({
title: "上传身份证正面图片错误,请重新上传",
icon: "error",
duration: 2000,
});
this.form2.individual_id_images == "";
this.fileList5 = [];
break;
case "ID_CARD_BEHIND":
uni.showToast({
title: "上传身份证反面图片错误,请重新上传",
icon: "error",
duration: 2000,
});
this.form2.individual_id_images2 == "";
this.fileList6 = [];
break;
case "BUSINESS_LICENCE":
uni.showToast({
title: "营业图片上传有误,请重新上传",
icon: "error",
duration: 2000,
});
this.form.biz_license_image == "";
this.fileList = [];
break;
}
}
clearTimeout(this.orcTimeout);
this.loading = false;
resolve(imgOcrRes?.data);
}, 1000);
});
},
/**判断文件类型是否正确 */
isAssetTypeAnImage(ext) {
const str = ext.split('.')[1];
return this.limitType.indexOf(str.toLowerCase()) !== -1;
},
getCompressionRatio(fileSize) {
const multiple = (fileSize / this.fileMaxSize).toFixed(2);
let compressionRatio = 1;
if (multiple > 5) {
compressionRatio = 0.5
} else if (multiple > 4) {
compressionRatio = 0.6
} else if (multiple > 3) {
compressionRatio = 0.7
} else if (multiple > 2) {
compressionRatio = 0.8
} else if (multiple > 1) {
compressionRatio = 0.9
} else {
compressionRatio = 2
}
return compressionRatio;
},
translate(imgSrc, scale) {
//imgSrc:
//scale: 0-1
return new Promise((reslove, reject) => {
var img = new Image(); //Image<img>
img.src = imgSrc; //<img>src
img.onload = () => {//onloadonload
var h = img.height/2; //
var w = img.width/2; //,
var canvas = document.createElement('canvas');//
var ctx = canvas.getContext('2d'); //2d
var width = document.createAttribute("width"); //
width.nodeValue = w; //
var height = document.createAttribute("height");
height.nodeValue = h;
canvas.setAttributeNode(width); //
canvas.setAttributeNode(height);
ctx.drawImage(img, 0, 0, w,h);//
//img: 0,0: w,h:
var base64 = canvas.toDataURL('image/png', scale);
//'image/png': scale:
//base64
canvas = null; //
var blob = this.base64ToBlob(base64); //
let blobUrl = window.URL.createObjectURL(blob);//blob
reslove(blobUrl)
}
})
},
// base64Blob
base64ToBlob(base64) {
var arr = base64.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime,
});
const str = ext.split(".")[1];
return this.limitType.indexOf(str.toLowerCase()) !== -1;
},
//
async afterRead(event, type) {
var item = event.file;
console.log("压缩前:",item.url);
var a = await this.translate(item.url,0.9)
item.url = a;
// let lists = [].concat(event.file);
// let fileListLen = this[`fileList${event.name}`].length;
// for (let index in lists) {
// const fileItem = lists[index];
// const fileSize = fileItem.size;
// const fileName = fileItem.name ?? '';
// if(!this.isAssetTypeAnImage(fileItem.name)) {
// this.$.msg('');
// return false
// }
// console.log('',fileSize);
// if (fileSize > this.fileMaxSize) {
// const compressionRatio = this.getCompressionRatio(fileSize);
// if (compressionRatio > 1) {
// uni.$u.toast("5MB!");
// return false
// }
// // 1M
// item = await this.handerCompressImg(fileItem, compressionRatio)
// if (fileItem.size > this.maxSize) {
// uni.$u.toast("5MB!");
// return false
// }
// }
// if (fileItem.size < this.fileMinSize) {
// uni.$u.toast("5MB!");
// return false
// }
// }
console.log("压缩后:",item.url);
var imgUrl = item.url;
const group = {
url: imgUrl,
@ -929,7 +872,7 @@ export default {
this.fileList6.push(group);
break;
}
console.log(imgUrl)
console.log(imgUrl);
let res = await UploadFilePromise(imgUrl);
if (res && res.status == 200) {
@ -1099,7 +1042,7 @@ export default {
this.$refs.uToast.show({
message: "请上营业执照片",
type: "error",
duration: 1000,
duration: 2000,
});
return;
}
@ -1108,7 +1051,7 @@ export default {
// this.$refs.uToast.show({
// message: "",
// type: "error",
// duration: 1000,
// duration: 2000,
// });
// return;
// }
@ -1117,7 +1060,7 @@ export default {
this.$refs.uToast.show({
message: "请上身份证图片正面照片",
type: "error",
duration: 1000,
duration: 2000,
});
return;
}
@ -1126,7 +1069,7 @@ export default {
this.$refs.uToast.show({
message: "请上身份证图片反面照片",
type: "error",
duration: 1000,
duration: 2000,
});
return;
}
@ -1154,7 +1097,7 @@ export default {
this.$refs.uToast.show({
message: "请上身份证图片反面照片",
type: "error",
duration: 1000,
duration: 2000,
});
return;
}
@ -1163,7 +1106,7 @@ export default {
this.$refs.uToast.show({
message: "请上身份证图片反面照片",
type: "error",
duration: 1000,
duration: 2000,
});
return;
}

View File

@ -172,7 +172,7 @@ import { batchNoApi, imgOcrResultApi } from "../../api/upload";
import { mapState } from "vuex";
import { throttle, debounce } from "lodash";
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
import { compressImg } from '@/utils/tool.js'
import { H5compressImg } from "@/utils/tool.js";
const orcImgTypeConf = {
FR_ID_CARD_FRONT: "FR_ID_CARD_FRONT",
@ -231,9 +231,9 @@ export default {
},
],
},
limitType: ['png', 'jpg', 'jpeg'], //
limitType: ["png", "jpg", "jpeg"], //
fileMaxSize: 1 * 1024 * 1024, // 1M
maxSize:5 * 1024 * 1024, //20M
maxSize: 5 * 1024 * 1024, //20M
fileMinSize: 5 * 1024, // 5KB
};
},
@ -263,67 +263,33 @@ export default {
},
compressImage(url) {
return new Promise((reslove, reject) => {
const tempFilePath = url //url
uni.compressImage({
const tempFilePath = url; //url
uni.compressImage({
src: tempFilePath,
quality: 90, //
success: (res) => {
reslove(res.tempFilePath) //
reslove(res.tempFilePath); //
},
fail: (error) => {
console.log('压缩失败', error)
}
})
})
},
async handerCompressImg(source, compressionRatio) {
let that = this;
return new Promise((resolve, reject) => {
compressImg(source.url, compressionRatio, source.type, compressRes => {
resolve(compressRes);
})
}).then((res) => {
source.size = res.size
// window.URL.revokeObjectURL(source.url) // ,
source.url = res.source
source.thumb = res.source
return source
}).catch(err => {
console.log('图片压缩失败', err)
})
},
/**判断文件类型是否正确 */
isAssetTypeAnImage(ext) {
const str = ext.split('.')[1];
return this.limitType.indexOf(str.toLowerCase()) !== -1;
},
getCompressionRatio(fileSize) {
const multiple = (fileSize / this.fileMaxSize).toFixed(2);
let compressionRatio = 1;
if (multiple > 5) {
compressionRatio = 0.5
} else if (multiple > 4) {
compressionRatio = 0.6
} else if (multiple > 3) {
compressionRatio = 0.7
} else if (multiple > 2) {
compressionRatio = 0.8
} else if (multiple > 1) {
compressionRatio = 0.9
} else {
compressionRatio = 2
}
return compressionRatio;
console.log("压缩失败", error);
},
});
});
},
getOcrText(filePath, file, type) {
//#ifdef APP-PLUS
filePath = await this.compressImage(filePath);
//#endif
return new Promise(async (resolve, reject) => {
this.loading = true;
//#ifdef APP-PLUS
filePath = await this.compressImage(filePath);
//#endif
// base64
//#ifdef H5
filePath = await H5compressImg(filePath, 0.75);
//#endif
const batchNoRes = await batchNoApi(filePath, file, type);
const batchNo = batchNoRes.batchNo;
@ -356,6 +322,17 @@ export default {
this.showBankDialog = true;
resolve(imgOcrRes?.data);
} else {
uni.showToast({
title: "银行号图片上传错误,请重新上传",
icon: "error",
duration: 2000,
});
this.form = {
branch_name: "",
account_number: "",
account_holder_name: "",
};
this.bankCardFiles = [];
reject(imgOcrRes);
}
@ -385,40 +362,6 @@ export default {
url: imgUrl,
};
let lists = [].concat(event.file);
let fileListLen = this[`fileList${event.name}`].length;
for (let index in lists) {
const group = lists[index];
const fileSize = group.size;
const fileName = group.name ?? '';
if(!this.isAssetTypeAnImage(group.name)) {
this.$.msg('不允许该文件类型上传');
return false
}
console.log('文件大小',fileSize);
if (fileSize > this.fileMaxSize) {
const compressionRatio = this.getCompressionRatio(fileSize);
if (compressionRatio > 1) {
this.$.msg('文件' + fileName + '大于5M');
return false
}
// 1M
item = await this.handerCompressImg(item, compressionRatio)
if (item.size > this.maxSize) {
this.$.msg('文件' + fileName + '压缩后超出20M')
return false
}
}
if (item.size < this.fileMinSize) {
this.$.msg('文件' + fileName + '不能小于5KB');
return false
}
}
console.log(e);
this.currentBankFile = {
file: item,
path: imgUrl,

View File

@ -65,6 +65,7 @@
:height="60"
:auto-height="true"
style="margin-bottom: 20rpx"
:maxlength="4"
>
<template slot="prefix">
<text class="input-label">验证码</text>

View File

@ -54,6 +54,7 @@
:height="60"
:auto-height="true"
:placeholder-style="'color: #999999;'"
:maxlength="showPassWord() == 'number' ? 4 : 99"
>
<template slot="prefix">
<text class="input-label">
@ -98,6 +99,7 @@
:auto-height="true"
:placeholder-style="'color: #999999;'"
style="margin-bottom: 20rpx"
:maxlength="4"
>
<template slot="prefix">
<text class="input-label">验证码</text>

View File

@ -35,6 +35,7 @@
:auto-height="true"
:placeholder-style="'color: #999999;'"
style="margin-bottom: 20rpx"
:maxlength="4"
>
<template slot="prefix">
<text class="input-label">验证码</text>

View File

@ -4,72 +4,68 @@
* scale 压缩质量 0-1
* type 文件类型
*/
export function compressImg (imgSrc, scale, type, callback) {
// uni.$u.toast('压缩中')
var img = new Image();
img.src = imgSrc;
img.onload = function() {
var that = this;
var h = (img.height * scale).toFixed(0); // 默认按质量比例压缩
var w = (img.width * scale).toFixed(0);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = document.createAttribute("width");
width.nodeValue = w;
var height = document.createAttribute("height");
height.nodeValue = h;
canvas.setAttributeNode(width);
canvas.setAttributeNode(height);
ctx.drawImage(that, 0, 0, w, h);
var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
canvas = null;
if (type == 'base64') {
let data = {
size: getBase64Size(base64),
type: type,
source: base64
}
callback(base64);
} else {
let blob = base64ToBlob(base64);
console.log('压缩后的大小', blob.size);
const blobUrl = window.URL.createObjectURL(blob); //blob地址
blob.source = blobUrl
callback(blob);
}
}
};
export async function H5compressImg(imgSrc, scale) {
//imgSrc:图片的路径
//scale:缩放比例 0-1之间
return new Promise((reslove, reject) => {
var img = new Image(); //创建Image对象生成一个<img>标签
img.src = imgSrc; //将图片路径赋给<img>标签的src
img.onload = () => {
//onload在图片加载成功后触发在onload中完成压缩功能
var h = img.height / 2; // 获取原本图片的宽高
var w = img.width / 2; //默认按比例压缩,根据需求修改
var canvas = document.createElement("canvas"); //创建画布
var ctx = canvas.getContext("2d"); //设置为2d效果
var width = document.createAttribute("width"); //创建属性节点
width.nodeValue = w; //设置属性值
var height = document.createAttribute("height");
height.nodeValue = h;
canvas.setAttributeNode(width); //设置画布宽高
canvas.setAttributeNode(height);
ctx.drawImage(img, 0, 0, w, h); //将图片贴到画布上
//img:图片 0,0:粘贴的位置 w,h:粘贴图片的大小
var base64 = canvas.toDataURL("image/png", scale);
//'image/png':压缩返回图片的类型 scale:图片质量
//如果要base64的流可以直接将结果返回了
canvas = null; //清除画布
// var blob = base64ToBlob(base64); //需要二进制流调用该方法拿到
// let blobUrl = window.URL.createObjectURL(blob); //blob地址
reslove(base64);
};
});
}
/**base转Blob */
export function base64ToBlob (base64) {
var arr = base64.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
};
export function base64ToBlob(base64) {
var arr = base64.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime,
});
}
/**获取base64的文件大小 */
export function getBase64Size () {
let size = 0;
if (base64Str) { // 获取base64图片byte大小
const equalIndex = base64Str.indexOf('='); // 获取=号下标
if (equalIndex > 0) {
const str = base64Str.substring(0, equalIndex); // 去除=号
const strLength = str.length;
const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
size = Math.floor(fileLength); // 向下取整
} else {
const strLength = base64Str.length;
const fileLength = strLength - (strLength / 8) * 2;
size = Math.floor(fileLength); // 向下取整
}
} else {
size = null;
}
return size
};
export function getBase64Size(base64Str) {
let size = 0;
if (base64Str) {
// 获取base64图片byte大小
const equalIndex = base64Str.indexOf("="); // 获取=号下标
if (equalIndex > 0) {
const str = base64Str.substring(0, equalIndex); // 去除=号
const strLength = str.length;
const fileLength = strLength - (strLength / 8) * 2; // 真实的图片byte大小
size = Math.floor(fileLength); // 向下取整
} else {
const strLength = base64Str.length;
const fileLength = strLength - (strLength / 8) * 2;
size = Math.floor(fileLength); // 向下取整
}
} else {
size = null;
}
return size;
}