imageUtils.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * @param {file}
  3. * @returns {string} 转Base64文件
  4. */
  5. export function getBase64(file:any) {
  6. return new Promise((resolve, reject) => {
  7. ///FileReader类就是专门⽤来读⽂件的
  8. const reader = new FileReader();
  9. //开始读⽂件
  10. //readAsDataURL: dataurl它的本质就是图⽚的⼆进制数据,进⾏base64加密后形成的⼀个字符串,
  11. reader.readAsDataURL(file);
  12. // 成功和失败返回对应的信息,reader.result⼀个base64,可以直接使⽤
  13. reader.onload = () => resolve(reader.result);
  14. // 失败返回失败的信息
  15. reader.onerror = (error) => reject(error);
  16. });
  17. }
  18. /**
  19. * @param {base64url}
  20. * @returns {string} // 获取文件得大小
  21. */
  22. export function calSize(base64url:string) {
  23. let str = base64url.replace('data:image/png;base64,', '');
  24. const equalIndex = str.indexOf('=');
  25. if(str.indexOf('=') > 0) {
  26. str = str.substring(0, equalIndex);
  27. }
  28. const strLength = str.length;
  29. const fileLength = strLength - (strLength / 8) * 2;
  30. // 返回单位为MB的大小
  31. return parseFloat((fileLength / (1024 * 1024)).toFixed(2));
  32. }
  33. /**
  34. * @param {path,w,callback}
  35. * @returns {callback} // 通过canvas压缩base64图片 并压缩
  36. */
  37. export function dealImage(path:string, w=1000, callback:any){
  38. const newImage = new Image();
  39. const size=calSize(path);//获取mb大小
  40. let quality = 0.52
  41. if(size<=1){//1 mb
  42. quality=0.9;
  43. }
  44. if(size>1){
  45. quality = 0.8
  46. }
  47. newImage.src = path;
  48. newImage.setAttribute("crossOrigin", 'Anonymous'); // url为外域时需要
  49. let imgWidth;
  50. let imgHeight;
  51. newImage.onload = function() {
  52. imgWidth = newImage.width;
  53. imgHeight = newImage.height;
  54. const canvas = document.createElement("canvas");
  55. const ctx = canvas.getContext("2d") as any;
  56. if (Math.max(imgWidth, imgHeight) > w) {
  57. if (imgWidth > imgHeight) {
  58. canvas.width = w;
  59. canvas.height = w * imgHeight / imgWidth;
  60. } else {
  61. canvas.height = w;
  62. canvas.width = w * imgWidth / imgHeight;
  63. }
  64. } else {
  65. canvas.width = imgWidth;
  66. canvas.height = imgHeight;
  67. }
  68. ctx.clearRect(0, 0, canvas.width, canvas.height);
  69. ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
  70. const newBase64 = canvas.toDataURL("image/jpeg", quality);
  71. callback(newBase64);
  72. }
  73. }
  74. /**
  75. * 统一批量导出
  76. * @method getBase64 文件转base64
  77. * @method dealImage 压缩图片
  78. * @method calSize 获取图片大小
  79. */
  80. const other = {
  81. base64: (file:any) => {
  82. return getBase64(file)
  83. },
  84. getDealImage:(path:any, w:number, callback:any)=>{
  85. return dealImage(path, w, callback)
  86. },
  87. getCalSize:(url:string)=>{
  88. return calSize(url)
  89. }
  90. }