Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I strip the data:image part from a base64 string of any image type in Javascript

Tags:

I am currently doing the following to decode base64 images in Javascript:

    var strImage = "";
    strImage = strToReplace.replace("data:image/jpeg;base64,", "");
    strImage = strToReplace.replace("data:image/png;base64,", "");
    strImage = strToReplace.replace("data:image/gif;base64,", "");
    strImage = strToReplace.replace("data:image/bmp;base64,", "");

As you can see above we are accepting the four most standard image types (jpeg, png, gif, bmp);

However, some of these images are very large and scanning through each one 4-5 times with replace seems a dreadful waste and terribly inefficient.

Is there a way I could reliably strip the data:image part of a base64 image string in a single pass?

Perhaps by detecting the first comma in the string?

Thanks in advance.

like image 765
Sergio Domínguez Avatar asked Jul 28 '16 09:07

Sergio Domínguez


People also ask

How do I decrypt a Base64 string?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

How do I view Base64 encoded images?

Images encoded with Base64 can be embedded in HTML by using the <img> tag. This can help to increase the page load time for smaller images by saving the browser from making additional HTTP requests.

How can I convert an image into Base64 string using Java?

Convert Image File to Base64 String byte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);


2 Answers

You can use a regular expression:

var strImage = strToReplace.replace(/^data:image\/[a-z]+;base64,/, "");

  • ^ means At the start of the string
  • data:image means data:image
  • \/ means /
  • [a-z]+ means One or more characters between a and z
  • ;base64, means ;base64,
like image 137
Nicolò Avatar answered Sep 17 '22 00:09

Nicolò


var solution = string.split("base64,")[1];

Splits the variable string at "base64," than take the second part.

like image 21
Jonas Wilms Avatar answered Sep 19 '22 00:09

Jonas Wilms