开发者社区> 问答> 正文

[分享]宜搭上传组件实现图片强制压缩(源码)

宜搭上传组件实现图片强制压缩(源码)

使用方法,将实现代码粘贴到宜搭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 < e && _extends(r, parseOrientation(e))) : r.url = URL.createObjectURL(n) : r.url = t, o.load(r) }, e.onabort = function () { o.fail(new Error("Aborted to read the image with FileReader.")) }, e.onerror = function () { o.fail(new Error("Failed to read the image with FileReader.")) }, e.onloadend = function () { o.reader = null }, a ? e.readAsArrayBuffer(n) : e.readAsDataURL(n))) : this.fail(new Error("The current browser does not support image compression.")) : this.fail(new Error("The first argument must be an image File or Blob object.")) : this.fail(new Error("The first argument must be a File or Blob object.")) } }, { key: "load", value: function (e) { var t = this, r = this.file, i = this.image; i.onload = function () { t.draw(_objectSpread2(_objectSpread2({}, e), {}, { naturalWidth: i.naturalWidth, naturalHeight: i.naturalHeight })) }, i.onabort = function () { t.fail(new Error("Aborted to load the image.")) }, i.onerror = function () { t.fail(new Error("Failed to load the image.")) }, WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent) && (i.crossOrigin = "anonymous"), i.alt = r.name, i.src = e.url } }, { key: "draw", value: function (e) { var t = this, r = e.naturalWidth, i = e.naturalHeight, a = e.rotate, o = void 0 === a ? 0 : a, n = e.scaleX, s = void 0 === n ? 1 : n, l = e.scaleY, c = void 0 === l ? 1 : l, h = this.file, u = this.image, d = this.options, f = document.createElement("canvas"), m = f.getContext("2d"), b = Math.abs(o) % 180 == 90, p = ("contain" === d.resize || "cover" === d.resize) && isPositiveNumber(d.width) && isPositiveNumber(d.height), g = Math.max(d.maxWidth, 0) || 1 / 0, y = Math.max(d.maxHeight, 0) || 1 / 0, v = Math.max(d.minWidth, 0) || 0, a = Math.max(d.minHeight, 0) || 0, n = r / i, e = d.width, l = d.height; b && (g = (w = [y, g])[0], y = w[1], v = (w = [a, v])[0], a = w[1], e = (w = [l, e])[0], l = w[1]); var w = getAdjustedSizes({ aspectRatio: n = p ? e / l : n, width: g, height: y }, "contain"); g = w.width, y = w.height; w = getAdjustedSizes({ aspectRatio: n, width: v, height: a }, "cover"); v = w.width, a = w.height, l = p ? (e = (w = getAdjustedSizes({ aspectRatio: n, width: e, height: l }, d.resize)).width, w.height) : (e = void 0 === (R = (O = getAdjustedSizes({ aspectRatio: n, width: e, height: l })).width) ? r : R, void 0 === (R = O.height) ? i : R); var O = -(e = Math.floor(normalizeDecimalNumber(Math.min(Math.max(e, v), g)))) / 2, R = -(l = Math.floor(normalizeDecimalNumber(Math.min(Math.max(l, a), y)))) / 2, v = e, g = l, a = []; p && (y = (n = getAdjustedSizes({ aspectRatio: n, width: y = r, height: p = i }, { contain: "cover", cover: "contain" }[d.resize])).width, p = n.height, a.push((r - y) / 2, (i - p) / 2, y, p)), a.push(O, R, v, g), b && (e = (U = [l, e])[0], l = U[1]), f.width = e, f.height = l, isImageType(d.mimeType) || (d.mimeType = h.type); var U = "transparent"; h.size > d.convertSize && 0 <= d.convertTypes.indexOf(d.mimeType) && (d.mimeType = "image/jpeg"), "image/jpeg" === d.mimeType && (U = "#fff"), m.fillStyle = U, m.fillRect(0, 0, e, l), d.beforeDraw && d.beforeDraw.call(this, m, f), this.aborted || (m.save(), m.translate(e / 2, l / 2), m.rotate(o * Math.PI / 180), m.scale(s, c), m.drawImage.apply(m, [u].concat(a)), m.restore(), d.drew && d.drew.call(this, m, f), this.aborted || (m = function (e) { t.aborted || t.done({ naturalWidth: r, naturalHeight: i, result: e }) }, f.toBlob ? f.toBlob(m, d.mimeType, d.quality) : m(toBlob(f.toDataURL(d.mimeType, d.quality))))) } }, { key: "done", value: function (e) { var t = e.naturalWidth, r = e.naturalHeight, i = e.result, a = this.file, o = this.image, e = this.options; URL && !e.checkOrientation && URL.revokeObjectURL(o.src), !i || e.strict && i.size > a.size && e.mimeType === a.type && !(e.width > t || e.height > r || e.minWidth > t || e.minHeight > r || e.maxWidth < t || e.maxHeight < r) ? i = a : (r = new Date, i.lastModified = r.getTime(), i.lastModifiedDate = r, i.name = a.name, i.name && i.type !== a.type && (i.name = i.name.replace(REGEXP_EXTENSION, imageTypeToExtension(i.type)))), this.result = i, e.success && e.success.call(this, i) } }, { key: "fail", value: function (e) { var t = this.options; if (!t.error) throw e; t.error.call(this, e) } }, { key: "abort", value: function () { this.aborted || (this.aborted = !0, this.reader ? this.reader.abort() : this.image.complete ? this.fail(new Error("The compression process has been aborted.")) : (this.image.onload = null, this.image.onabort())) } }], [{ key: "noConflict", value: function () { return window.Compressor = AnotherCompressor, r } }, { key: "setDefaults", value: function (e) { _extends(DEFAULTS, e) } }]), r }();
var closeLoading;
export function poptoastLoading(title_str, s) {
  closeLoading = this.utils.toast({
    title: title_str,
    type: 'loading',
    size: "large"
  });
  if (s != 0) {
    setTimeout(() => {
      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 < selectedFiles.length; i++) {
    const fileEx = selectedFiles[i].name.match(/\.(png|jpe?g|bmp)(\?.*)?$/);
    if (!fileEx) {
      console.log('不是图片');
      continue;
    };

    const fileItem = selectedFiles[i];
    await fileToBlob(fileItem).then(res => {
      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');
}

展开
收起
页一  2022-11-03 09:34:06 2926 2
来自:钉钉宜搭
1 条回答
写回答
取消 提交回答
  • 在图片上传设定为必填后,在手机端压缩不成功。取消必填后正常。

    2022-12-29 19:54:56
    赞同 1 展开评论 打赏
问答分类:
问答地址:
关联地址:
相关产品:
来源圈子
更多
收录在圈子:
+ 订阅
「宜搭」是云钉原生低代码平台(钉钉 PaaS - aPaaS),让企业应用搭建更简单! 帮助中小企业降本提效,加强组织的数字化自主权; 帮助大型企业释放个体创新力,助力组织创新涌现。
相关文档: 宜搭
问答排行榜
最热
最新

相关电子书

更多
宜搭 - 企业智能化应用搭建平台 立即下载
《云市场-宜搭解决方案》 立即下载
《宜搭开发手册》 立即下载