宜搭上传组件实现图片强制压缩(源码)
使用方法,将实现代码粘贴到宜搭js面板就行了
该压缩功能宜搭官方已经在开发,着急刚需的可以先使用这个源码.
"use strict"; function ownKeys(t, e) { var r, i = Object.keys(t); return Object.getOwnPropertySymbols && (r = Object.getOwnPropertySymbols(t), e && (r = r.filter(function (e) { return Object.getOwnPropertyDescriptor(t, e).enumerable })), i.push.apply(i, r)), i } function _objectSpread2(t) { for (var e = 1; e < arguments.length; e++) { var r = null != arguments[e] ? arguments[e] : {}; e % 2 ? ownKeys(Object(r), !0).forEach(function (e) { _defineProperty(t, e, r[e]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(r)) : ownKeys(Object(r)).forEach(function (e) { Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(r, e)) }) } return t } function _classCallCheck(e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") } function _defineProperties(e, t) { for (var r = 0; r < t.length; r++) { var i = t[r]; i.enumerable = i.enumerable || !1, i.configurable = !0, "value" in i && (i.writable = !0), Object.defineProperty(e, i.key, i) } } function _createClass(e, t, r) { return t && _defineProperties(e.prototype, t), r && _defineProperties(e, r), e } function _defineProperty(e, t, r) { return t in e ? Object.defineProperty(e, t, { value: r, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = r, e } function _extends() { return (_extends = Object.assign || function (e) { for (var t = 1; t < arguments.length; t++) { var r, i = arguments[t]; for (r in i) Object.prototype.hasOwnProperty.call(i, r) && (e[r] = i[r]) } return e }).apply(this, arguments) } var canvasToBlob = { exports: {} }; !function (e) { var t, a, s, l, c, h, o; "undefined" != typeof window && (a = (t = window).HTMLCanvasElement && t.HTMLCanvasElement.prototype, s = t.Blob && function () { try { return Boolean(new Blob) } catch (e) { return !1 } }(), l = s && t.Uint8Array && function () { try { return 100 === new Blob([new Uint8Array(100)]).size } catch (e) { return !1 } }(), c = t.BlobBuilder || t.WebKitBlobBuilder || t.MozBlobBuilder || t.MSBlobBuilder, h = /^data:((.*?)(;charset=.*?)?)(;base64)?,/, o = (s || c) && t.atob && t.ArrayBuffer && t.Uint8Array && function (e) { var t, r, i, a, o, n = e.match(h); if (!n) throw new Error("invalid data URI"); for (t = n[2] ? n[1] : "text/plain" + (n[3] || ";charset=US-ASCII"), i = !!n[4], n = e.slice(n[0].length), r = (i ? atob : decodeURIComponent)(n), i = new ArrayBuffer(r.length), a = new Uint8Array(i), o = 0; o < r.length; o += 1)a[o] = r.charCodeAt(o); return s ? new Blob([l ? a : i], { type: t }) : ((n = new c).append(i), n.getBlob(t)) }, t.HTMLCanvasElement && !a.toBlob && (a.mozGetAsFile ? a.toBlob = function (e, t, r) { var i = this; setTimeout(function () { r && a.toDataURL && o ? e(o(i.toDataURL(t, r))) : e(i.mozGetAsFile("blob", t)) }) } : a.toDataURL && o && (a.msToBlob ? a.toBlob = function (e, t, r) { var i = this; setTimeout(function () { (t && "image/png" !== t || r) && a.toDataURL && o ? e(o(i.toDataURL(t, r))) : e(i.msToBlob(t)) }) } : a.toBlob = function (e, t, r) { var i = this; setTimeout(function () { e(o(i.toDataURL(t, r))) }) })), e.exports ? e.exports = o : t.dataURLtoBlob = o) }(canvasToBlob); var toBlob = canvasToBlob.exports, isBlob = function (e) { return "undefined" != typeof Blob && (e instanceof Blob || "[object Blob]" === Object.prototype.toString.call(e)) }, DEFAULTS = { strict: !0, checkOrientation: !0, maxWidth: 1 / 0, maxHeight: 1 / 0, minWidth: 0, minHeight: 0, width: void 0, height: void 0, resize: "none", quality: .8, mimeType: "auto", convertTypes: ["image/png"], convertSize: 5e6, beforeDraw: null, drew: null, success: null, error: null }, IS_BROWSER = "undefined" != typeof window && void 0 !== window.document, WINDOW = IS_BROWSER ? window : {}, isPositiveNumber = function (e) { return 0 < e && e < 1 / 0 }, slice = Array.prototype.slice; function toArray(e) { return Array.from ? Array.from(e) : slice.call(e) } var REGEXP_IMAGE_TYPE = /^image\/.+$/; function isImageType(e) { return REGEXP_IMAGE_TYPE.test(e) } function imageTypeToExtension(e) { e = isImageType(e) ? e.substr(6) : ""; return ".".concat(e = "jpeg" === e ? "jpg" : e) } var fromCharCode = String.fromCharCode; function getStringFromCharCode(e, t, r) { var i, a = ""; for (r += t, i = t; i < r; i += 1)a += fromCharCode(e.getUint8(i)); return a } var btoa = WINDOW.btoa; function arrayBufferToDataURL(e, t) { for (var r = [], i = new Uint8Array(e); 0 < i.length;)r.push(fromCharCode.apply(null, toArray(i.subarray(0, 8192)))), i = i.subarray(8192); return "data:".concat(t, ";base64,").concat(btoa(r.join(""))) } function resetAndGetOrientation(e) { var t, r, i, a, o, n, s, l = new DataView(e); try { if (255 === l.getUint8(0) && 216 === l.getUint8(1)) for (var c = l.byteLength, h = 2; h + 1 < c;) { if (255 === l.getUint8(h) && 225 === l.getUint8(h + 1)) { r = h; break } h += 1 } if (r && (a = r + 10, "Exif" === getStringFromCharCode(l, r + 4, 4) && (!(s = 18761 === (o = l.getUint16(a))) && 19789 !== o || 42 !== l.getUint16(a + 2, s) || 8 <= (n = l.getUint32(a + 4, s)) && (i = a + n))), i) for (var u, d = l.getUint16(i, s), f = 0; f < d; f += 1)if (u = i + 12 * f + 2, 274 === l.getUint16(u, s)) { u += 8, t = l.getUint16(u, s), l.setUint16(u, 1, s); break } } catch (e) { t = 1 } return t } function parseOrientation(e) { var t = 0, r = 1, i = 1; switch (e) { case 2: r = -1; break; case 3: t = -180; break; case 4: i = -1; break; case 5: t = 90, i = -1; break; case 6: t = 90; break; case 7: t = 90, r = -1; break; case 8: t = -90 }return { rotate: t, scaleX: r, scaleY: i } } var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/; function normalizeDecimalNumber(e) { var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : 1e11; return REGEXP_DECIMALS.test(e) ? Math.round(e * t) / t : e } function getAdjustedSizes(e) { var t = e.aspectRatio, r = e.height, i = e.width, a = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : "none", o = isPositiveNumber(i), n = isPositiveNumber(r); return o && n ? (e = r * t, ("contain" === a || "none" === a) && i < e || "cover" === a && e < i ? r = i / t : i = r * t) : o ? r = i / t : n && (i = r * t), { width: i, height: r } } var ArrayBuffer$1 = WINDOW.ArrayBuffer, FileReader = WINDOW.FileReader, URL = WINDOW.URL || WINDOW.webkitURL, REGEXP_EXTENSION = /\.\w+$/, AnotherCompressor = WINDOW.Compressor, Compressor = function () { function r(e, t) { _classCallCheck(this, r), this.file = e, this.image = new Image, this.options = _objectSpread2(_objectSpread2({}, DEFAULTS), t), this.aborted = !1, this.result = null, this.init() } return _createClass(r, [{ key: "init", value: function () { var i, e, a, o = this, n = this.file, t = this.options; isBlob(n) ? isImageType(i = n.type) ? URL && FileReader ? (ArrayBuffer$1 || (t.checkOrientation = !1), URL && !t.checkOrientation ? this.load({ url: URL.createObjectURL(n) }) : (e = new FileReader, a = t.checkOrientation && "image/jpeg" === i, (this.reader = e).onload = function (e) { var t = e.target.result, r = {}; a ? 1 < (e = resetAndGetOrientation(t)) || !URL ? (r.url = arrayBufferToDataURL(t, i), 1 d.convertSize && 0 a.size && e.mimeType === a.type && !(e.width > t || e.height > r || e.minWidth > t || e.minHeight > r || e.maxWidth < t || e.maxHeight {
this.onCloseLoading();
}, s * 1000);
}
}
export function onCloseLoading() {
if (closeLoading) {
closeLoading();
}
}
function dataURL2Blob2File(dataURL, file) {
const arr = dataURL.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
u8arr = new Uint8Array(bstr.length);
let n = bstr.length;
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
const blob = new Blob([u8arr], {
type: mime
});
blob.lastModifiedDate = new Date();
blob.name = file.name;
blob.uid = file.uid;
return blob
}
export function compressorImage(image, quality) {
return new Promise((resolve, reject) => {
new Compressor(image, {
quality: 0.6,
maxWidth: 1800,
maxHeight: 1400,
mimeType: 'image/jpeg',
success(result) {
result.lastModifiedDate = new Date();
result.name = image.name;
result.uid = image.uid;
resolve(result)
},
error(err) {
this.onCloseLoading();
console.log('图片压缩失败---->>>>>', err)
reject(err)
}
})
})
}
const fileToBlob = (blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(blob.originFileObj);
reader.onload = () => {
const file = dataURL2Blob2File(reader.result, blob);
resolve(file);
};
reader.onerror = error => reject('文件读取错误');
});
export async function cmpImg(selectedFiles, allFiles) {
let arrPromise = [];
for (let i = 0; i {
arrPromise.push(this.compressorImage(res));
}).catch(err => {
console.log(err.message)
})
}
await Promise.all(arrPromise).then(res => {
let newRes = {};
res.forEach(item => {
newRes[item.uid] = [item.size, item];
})
allFiles.forEach(item => {
if (newRes[item.uid]) {
item.size = newRes[item.uid][0];
item.originFileObj = newRes[item.uid][1];
}
})
}).catch(err => {
console.log(err.message)
});
return allFiles;
}
export async function compressImage(selectedFiles, allFiles, imageFiledId) {
this.poptoastLoading('正在压缩图片', 20);
const selectedFD = this.$(imageFiledId);
const newFiles = await this.cmpImg(selectedFiles, allFiles);
await selectedFD.setValue(newFiles);
this.utils.toast({
title: '开始上传',
type: 'notice',
size: 'large',
duration: 1000,
});
selectedFD.startUpload();
}
以上是压缩代码,下面是调用方法
//页面加载完毕 //需要实现压缩功能的组件ID attachmentField_l9s2g49z
export function didMount() {
this.$('attachmentField_l9s2g49z').set('autoUpload', false)
}
//上传组件的onSelect事件 //需要实现压缩功能的组件ID attachmentField_l9s2g49z
export function onSelect() {
let [selectedFile, allUpdateFile] = arguments;
this.compressImage(selectedFile, allUpdateFile, 'attachmentField_l9s2g49z');
}