Commit ae8eaaeaa31fd192a7509fb8cc4a7d263db1de61

Authored by ly525
1 parent 104107c1

perf(editor) compress cover image on client side before uploading

front-end/h5/src/utils/helper.js
1 1 import html2canvas from 'html2canvas'
2 2  
  3 +// https://stackoverflow.com/questions/12168909/blob-from-dataurl
  4 +function dataURItoBlob (dataURI) {
  5 + // convert base64 to raw binary data held in a string
  6 + // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  7 + var byteString = atob(dataURI.split(',')[1])
  8 +
  9 + // separate out the mime component
  10 + var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
  11 +
  12 + // write the bytes of the string to an ArrayBuffer
  13 + var ab = new ArrayBuffer(byteString.length)
  14 +
  15 + // create a view into the buffer
  16 + var ia = new Uint8Array(ab)
  17 +
  18 + // set the bytes of the buffer to the correct values
  19 + for (var i = 0; i < byteString.length; i++) {
  20 + ia[i] = byteString.charCodeAt(i)
  21 + }
  22 +
  23 + // write the ArrayBuffer to a blob, and you're done
  24 + var blob = new Blob([ab], { type: mimeString })
  25 + return blob
  26 +}
  27 +
3 28 /**
4 29 * 生成作品封面图(截图)
5 30 * @param {String} selector
... ... @@ -13,11 +38,15 @@ export function takeScreenshot (selector = &#39;.canvas-wrapper&#39;, fileName = `${+new
13 38 // if you use allowTaint: true, the cors image will taint the canvas, and canvas.toDataURL won't work
14 39 // 会对canvas造成污染,导致 canvas.toDataURL 无效
15 40 html2canvas(el, { proxy: '/works/cors-proxy' }).then(canvas => {
16   - // document.body.appendChild(canvas) use this line to test the generated canvas
17   - canvas.toBlob(blob => {
18   - const file = new window.File([blob], fileName, { type: 'image/png' })
19   - resolve(file)
20   - })
  41 + // https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
  42 + const dataUrl = canvas.toDataURL('image/jpeg', 0.6)
  43 + const blob = dataURItoBlob(dataUrl)
  44 + const file = new window.File([blob], fileName, { type: 'image/png' })
  45 + resolve(file)
  46 + // canvas.toBlob(blob => {
  47 + // const file = new window.File([blob], fileName, { type: 'image/png' })
  48 + // resolve(file)
  49 + // })
21 50 })
22 51 })
23 52 }
... ...