preface

Recently, I need to convert base64 images into File objects in JS for uploading, so I learned some knowledge about this aspect

Turn Base64 Blob

  1. Split Base64 data, generate file objects, Base64 -> Uint8Array -> Blob
function dataURI2Blob(dataURI) {
  // Split data
  const [meta, data] = dataURI.split(', ')
  // Encode the data
  let byte
  if (meta.includes('base64')) {
    byte = atob(data)
  } else {
    byte = encodeURI(data)
  }
  // Get the image format
  const mime = meta.split(':') [1].split('; ') [0]
  // Create an 8-bit unsigned integer array
  const ia = new Uint8Array(byte.length)
  // Get the character UTF-16 encoding value
  for (let i = 0; i < byte.length; i++) {
    ia[i] = byte.codePointAt(i)
  }
  // Generate file-like objects
  return new Blob([ia], { type: mime })
}
Copy the code

If you want to extend it, you can convert it to a File object

// Generate file objects
new File([ia], 'test.jpg', { type: mime })
Copy the code
  1. The trick is to use fetch
 async function dataURI2Blob(dataURI) {
   // Return bloB data
   const blob = await fetch(dataURI).then((res) = > res.blob())
   return blob
 }
Copy the code

I prefer the second one, because it is simple and easy to understand, with less code. Then you can upload the file

const fd = new FormData();
fd.append("img", blob, "test.jpg");
Copy the code

Turn the Blob Base64

Use FileReader to do the reverse conversion and convert File objects in the same way

function blob2Base64(blob, callback) {
  const reader = new FileReader()

  reader.addEventListener('load'.() = > {
    callback(reader.result)
  })

  reader.readAsDataURL(blob)
}
Copy the code

Expand the

Convert the remote Image to Base64 format, URL -> Image -> Canvas -> Base64

 function remoteImageToBase64(url, callback) {
  const img = new Image()
  let canvas = document.createElement('canvas')
  let context = canvas.getContext('2d')

  img.addEventListener('load'.() = > {
    canvas.width = img.width
    canvas.height = img.height
    context.drawImage(img, 0.0)

    // Return Base64 data or use the toBlob method to return Blob
    callback(canvas.toDataURL('image/jpg'.1))
    canvas = null
  })

  img.src = url
  // Handle Canvas cross-domain
  img.crossOrigin = 'Anonymous'
}

 remoteImageToBase64('https://game.gtimg.cn/images/lol/act/img/skin/big145014.jpg'.(res) = > {
   console.log('base64: ', res)
 })
Copy the code

You can also use fetch to type Blob

 async function remoteImageToBlob(url) {
   const blob = await fetch(url).then((res) = > res.blob())
   
   return blob
 }
Copy the code

After the