base64Conver.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @description: base64 to blob
  3. */
  4. export function dataURLtoBlob(base64Buf: string): Blob {
  5. const arr = base64Buf.split(',');
  6. const typeItem = arr[0];
  7. const mime = typeItem.match(/:(.*?);/)![1];
  8. const bstr = window.atob(arr[1]);
  9. let n = bstr.length;
  10. const u8arr = new Uint8Array(n);
  11. while (n--) {
  12. u8arr[n] = bstr.charCodeAt(n);
  13. }
  14. return new Blob([u8arr], { type: mime });
  15. }
  16. /**
  17. * img url to base64
  18. * @param url
  19. */
  20. export function fileToBase64(file: File): Promise<string | ArrayBuffer> {
  21. return new Promise((resolve, reject) => {
  22. if (!file) {
  23. reject();
  24. }
  25. const reader = new FileReader();
  26. reader.readAsDataURL(file);
  27. reader.onload = function (e) {
  28. const result = e.target.result;
  29. resolve(result);
  30. };
  31. });
  32. }
  33. /**
  34. * img url to base64
  35. * @param url
  36. */
  37. export function urlToBase64(url: string, mineType?: string): Promise<string> {
  38. return new Promise((resolve, reject) => {
  39. let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>;
  40. const ctx = canvas!.getContext('2d');
  41. const img = new Image();
  42. img.crossOrigin = '';
  43. img.onload = function () {
  44. if (!canvas || !ctx) {
  45. return reject();
  46. }
  47. canvas.height = img.height;
  48. canvas.width = img.width;
  49. ctx.drawImage(img, 0, 0);
  50. const dataURL = canvas.toDataURL(mineType || 'image/png');
  51. canvas = null;
  52. resolve(dataURL);
  53. };
  54. img.src = url;
  55. });
  56. }