JavaScript check if valid base64 image

12,166

Solution 1

I wrote an async function using @wolfshirts answer. It worked for me.

@wolfshirts function will not work because the return line was placed in the wrong scope.

async function isBase64UrlImage(base64String: string) {
  let image = new Image()
  image.src = base64String
  return await (new Promise((resolve)=>{
    image.onload = function () {
      if (image.height === 0 || image.width === 0) {
        resolve(false);
        return;
      }
      resolve(true)
    }
    image.onerror = () =>{
      resolve(false)
    }
  }))
}

Solution 2

I'm not sure if you're trying to validate the image itself, or the URL. Validating the image can be tricky. I would first run a check against known base64 MIME types.

'/' means jpeg.

'i' means png.

'R' means gif.

'U' means webp.

let data = //suspectedBase64Image
    
    
function isImage(data){
    let knownTypes = {
      '/': 'data:image/jpg;base64,',
      'i': 'data:image/png;base64,',
      /*ETC*/
      }
      
      let image = new Image()
      
      if(!knownTypes[data[0]]){
        console.log("encoded image didn't match known types");
        return false;
      }else{
        image.src = knownTypes[0]+data
        image.onload = function(){
          //This should load the image so that you can actually check
          //height and width.
          if(image.height === 0 || image.width === 0){
            console.log('encoded image missing width or height');
            return false;
          }
      }
      return true;
}

This is some basic sanity checking you could use.

You could go deeper and convert magic numbers to base64 then check for them within the base64 data. This code makes the assumption that you're missing the data type at the start. Some base64 will have the data type shown in the dictionary at the start of the base64.

Share:
12,166
Vetterjack
Author by

Vetterjack

Updated on July 26, 2022

Comments

  • Vetterjack
    Vetterjack over 1 year

    Is there an easy way to check if a base64 image url is valid? I'm getting the base64 url from server via ajax/xhr and want to avoid xss on my site.

  • Bruno Marotta
    Bruno Marotta over 2 years
    This won't work. You have to return a promise for it to work (how can you return false on an callback event ?!