function dataURLtoBlob(base64Buf) {
  const arr = base64Buf.split(",");
  const typeItem = arr[0];
  const mime = typeItem.match(/:(.*?);/)[1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}
function urlToBase64(url, mineType) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement("CANVAS");
    const ctx = canvas.getContext("2d");
    const img = new Image();
    img.crossOrigin = "";
    img.onload = function() {
      if (!canvas || !ctx) {
        return reject();
      }
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0);
      const dataURL = canvas.toDataURL(mineType || "image/png");
      canvas = null;
      resolve(dataURL);
    };
    img.src = url;
  });
}
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
function base64ToFile(dataURL, fileName, mimeType = null) {
  var arr = dataURL.split(",");
  var defaultMimeType = arr[0].match(/:(.*?);/)[1];
  var bStr = atob(arr[1]);
  let n = bStr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bStr.charCodeAt(n);
  }
  return new File([u8arr], fileName, { type: mimeType || defaultMimeType });
}
function blobToFile(blob, fileName, mimeType) {
  if (mimeType == null) mimeType = blob.type;
  return new File([blob], fileName, { type: mimeType });
}

export { base64ToFile, blobToFile, dataURLtoBlob, fileToBase64, urlToBase64 };
