imageMin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. class ImageMin {
  2. constructor (options) {
  3. this.file = options.file
  4. this.maxSize = options.maxSize || 1024 * 1024
  5. this.quantity = parseFloat((this.file.size / this.maxSize).toFixed(2))
  6. return new Promise((resolve, reject) => {
  7. if (this.quantity <= 1) {
  8. this.blobToDataURL(this.file).then(ev => {
  9. resolve({
  10. base64: ev.target.result,
  11. res: this.file
  12. })
  13. })
  14. } else {
  15. this.mini(resolve, reject)
  16. }
  17. })
  18. }
  19. mini (resolve, reject) {
  20. let { file, quantity } = this
  21. try {
  22. let reader = new FileReader()
  23. let img = new Image()
  24. reader.readAsDataURL(file)
  25. reader.onload = function (e) {
  26. img.src = e.target.result
  27. }
  28. img.onload = () => {
  29. // 缩放图片需要的canvas
  30. let canvas = document.createElement('canvas')
  31. let context = canvas.getContext('2d')
  32. // 图片原始尺寸
  33. let originWidth = img.width
  34. let originHeight = img.height
  35. canvas.width = originWidth
  36. canvas.height = originHeight
  37. // 清除画布
  38. context.clearRect(0, 0, originWidth, originHeight)
  39. // 图片压缩
  40. context.drawImage(img, 0, 0, originWidth, originHeight)
  41. let newRes = canvas.toDataURL('image/jpeg', quantity) // base64 格式
  42. let blob = this.dataURLtoBlob(newRes)
  43. if (blob.size > this.maxSize) {
  44. context.clearRect(0, 0, originWidth, originHeight)
  45. let scale = this.maxSize / blob.size * 0.8
  46. let targetWidth = parseInt(originWidth * scale)
  47. let targetHeight = parseInt(originHeight * scale)
  48. canvas.width = targetWidth
  49. canvas.height = targetHeight
  50. context.drawImage(img, 0, 0, originWidth, originHeight, 0, 0, targetWidth, targetHeight)
  51. newRes = canvas.toDataURL('image/jpeg')
  52. blob = this.dataURLtoBlob(newRes)
  53. }
  54. resolve({
  55. base64: newRes,
  56. res: blob
  57. })
  58. }
  59. } catch (e) {
  60. reject(e)
  61. }
  62. }
  63. blobToDataURL (blob) {
  64. return new Promise((resolve, reject) => {
  65. var fr = new FileReader()
  66. fr.onload = resolve
  67. fr.readAsDataURL(blob)
  68. })
  69. }
  70. dataURLtoBlob (dataurl) {
  71. let arr = dataurl.split(',')
  72. let mime = arr[0].match(/:(.*?);/)[1]
  73. let bstr = atob(arr[1])
  74. let n = bstr.length
  75. let u8arr = new Uint8Array(n)
  76. while (n--) {
  77. u8arr[n] = bstr.charCodeAt(n)
  78. }
  79. return new Blob([u8arr], { type: mime })
  80. }
  81. }
  82. export default ImageMin