Parse Image Base64 Extension in Javascript

Introduction

Parse the base64 data of the image in JavaScript and get its extension (file type)

code

Here's one way to do it:

function getImageExtensionFromBase64(base64Data) {
   const regex = /^data:image\/(\w+);base64,/; // regular expression matches base64 data header
   const matches = base64Data.match(regex);
  
   if (matches && matches. length === 2) {
     return matches[1]; // return the first capture group, which is the file extension
   }
  
   return null; // extension not found
}

// Example usage
const base64ImageData = "data:image/png;base64,iVBORw0KGg..."; // string containing base64 data
const extension = getImageExtensionFromBase64(base64ImageData);
console.log(extension); // output: png

In the above code, the getImageExtensionFromBase64 function receives a string containing base64 data, and uses a regular expression to match the header of the string to extract the file extension. The regular expression /^data:image\/(\w+);base64,/ is used to match strings starting with "data:image/", followed by the file extension, and then ";base64,". where \w+ matches one or more alphanumeric or underscore characters. If the match is successful, return the first capture group of the matching result (ie the file extension), otherwise return null indicating that the extension was not found.

Note that this method only works for images contained in base64 data. If the image does not have base64 data starting with "data:image/", or does not have an explicit file extension, then its extension cannot be determined from the base64 data. In this case, you may need some other way to get the image's extension.

Comments