base64ToBlob 图片的 base64 转 Blob 对象,用于生成本地图片

/**
 * 图片的 base64 转 Blob 对象,用于生成本地图片
 * @param {*} base64 String
 * @returns Blob
 */
const base64ToBlob = (base64Data) => {
  // Split base64
  const arr = base64Data.split(',')

  // Get MIME type
  const mimeMatch = arr[0].match(/:(.*?);/)

  if (!mimeMatch) {
    throw new Error('Invalid base64 data')
  }

  const mime = mimeMatch[1]
  // Decode base64 string
  let raw

  try {
    raw = window.atob(arr[1])
  } catch (e) {
    throw new Error('Failed to decode base64 string')
  }

  const rawLength = raw.length
  // Convert to Blob
  const uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; i++) {
    uInt8Array[i] = raw.charCodeAt(i)
  }

  return new Blob([uInt8Array], { type: mime })
}
posted @ 2024-11-25 16:17  龙陌  阅读(273)  评论(0)    收藏  举报