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.
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.
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.
Convert Image File to Base64 String byte[] fileContent = FileUtils. readFileToByteArray(new File(filePath)); String encodedString = Base64. getEncoder(). encodeToString(fileContent);
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,
var solution = string.split("base64,")[1];
Splits the variable string at "base64," than take the second part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With