base64Conver.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 urlToBase64(url: string, mineType?: string): Promise<string> {
  21. return new Promise((resolve, reject) => {
  22. let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>;
  23. const ctx = canvas!.getContext('2d');
  24. const img = new Image();
  25. img.crossOrigin = '';
  26. img.onload = function () {
  27. if (!canvas || !ctx) {
  28. return reject();
  29. }
  30. canvas.height = img.height;
  31. canvas.width = img.width;
  32. ctx.drawImage(img, 0, 0);
  33. const dataURL = canvas.toDataURL(mineType || 'image/png');
  34. canvas = null;
  35. resolve(dataURL);
  36. };
  37. img.src = url;
  38. });
  39. }
  40. /**
  41. * File转Base64
  42. * @param file
  43. */
  44. export function fileToBase64(file: Blob) {
  45. return new Promise((resolve, reject) => {
  46. const reader = new FileReader();
  47. reader.readAsDataURL(file);
  48. reader.onload = () => resolve(reader.result);
  49. reader.onerror = (error) => reject(error);
  50. });
  51. }
  52. /**
  53. * Base64转File
  54. * @param dataURL {String} base64
  55. * @param fileName {String} 文件名
  56. * @param mimeType {String} [可选]文件类型,默认为base64中的类型
  57. * @returns {File}
  58. */
  59. export function base64ToFile(dataURL: string, fileName: string, mimeType = null) {
  60. var arr = dataURL.split(',');
  61. var defaultMimeType = arr[0].match(/:(.*?);/)[1];
  62. var bStr = atob(arr[1]);
  63. let n = bStr.length;
  64. var u8arr = new Uint8Array(n);
  65. while (n--) {
  66. u8arr[n] = bStr.charCodeAt(n);
  67. }
  68. return new File([u8arr], fileName, { type: mimeType || defaultMimeType });
  69. }
  70. /**
  71. * Blob转File
  72. * @param blob {Blob} blob
  73. * @param fileName {String} 文件名
  74. * @param mimeType {String} 文件类型
  75. * @return {File}
  76. */
  77. export function blobToFile(blob: Blob, fileName: string, mimeType?: string) {
  78. if (mimeType == null) mimeType = blob.type;
  79. return new File([blob], fileName, { type: mimeType });
  80. }