compressImg.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. export function showSize (base64url) {
  2. let str = base64url.replace('data:image/png;base64,', '')
  3. // 找到等号,把等号也去掉
  4. const equalIndex = str.indexOf('=')
  5. if (str.indexOf('=') > 0) {
  6. str = str.substring(0, equalIndex)
  7. }
  8. // 原来的字符流大小,单位为字节
  9. const strLength = base64url.length
  10. // 计算后得到的文件流大小,单位为字节
  11. const fileLength = parseInt(strLength - (strLength / 8) * 2)
  12. // 由字节转换为kb
  13. let size = ''
  14. size = (fileLength / 1024).toFixed(2)
  15. const sizeStr = size + '' // 转成字符串
  16. const index = sizeStr.indexOf('.') // 获取小数点处的索引
  17. const dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  18. if (dou === '00') {
  19. // 判断后两位是否为00,如果是则删除00
  20. return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  21. }
  22. return size
  23. }
  24. export function dataURLtoFile (dataurl, filename) {
  25. // 将base64转换为文件,dataurl为base64字符串,filename为文件名(必须带后缀名,如.jpg,.png)
  26. const arr = dataurl.split(',')
  27. const mime = arr[0].match(/:(.*?);/)[1]
  28. const bstr = atob(arr[1])
  29. let n = bstr.length
  30. const u8arr = new Uint8Array(n)
  31. while (n--) {
  32. u8arr[n] = bstr.charCodeAt(n)
  33. }
  34. return new File([u8arr], filename, { type: mime })
  35. }
  36. export function dataURLtoBlob (dataurl) {
  37. const arr = dataurl.split(',')
  38. const _arr = arr[1].substring(0, arr[1].length - 2)
  39. const mime = arr[0].match(/:(.*?);/)[1]
  40. const bstr = atob(_arr)
  41. let n = bstr.length
  42. const u8arr = new Uint8Array(n)
  43. while (n--) {
  44. u8arr[n] = bstr.charCodeAt(n)
  45. }
  46. return new Blob([u8arr], {
  47. type: mime
  48. })
  49. }
  50. export function translateBlobToBase64 (blob, callback) {
  51. const reader = new FileReader()
  52. reader.onload = function (e) {
  53. callback(e.target)
  54. }
  55. reader.readAsDataURL(blob)
  56. // 读取后,result属性中将包含一个data:URL格式的Base64字符串用来表示所读取的文件
  57. }