Encode And Decode Base64 Data In Javascript And Java
Posted By : S. Ajit | 09-Apr-2017
Base64 is a generic encoding schemes that encode binary data by treating it numerically and translating it into a base 64 representation.
Lets first talk about encoding and decoding javascript, In javascript to encode a string we use btoa function. It is a global function that encode a string to base64 string and to decode the encoded base64 string we use atob function. Here is a example:
/***** Encoding And Decoding Base64 In Javascript ******/
var text = "Highlight";
// Encode the String
var encodedString = btoa(text);
console.log(encodedString); // Outputs: "SGlnaGxpZ2h0"
// Decode the String
var decodedString = cell (encodedString);
console.log(decodedString); // Outputs: "Highlight"
In java we use java.util's Base64 class to encode and decode base64 string. Here is a example:
/***** Encoding And Decoding Base64 In Java ******/
String str = "Highlight";
Encoder encoder = Base64.getEncoder();
String encodedString = encoder.encodeToString(str.getBytes());
System.out.println(encodedString); // Outputs: "SGlnaGxpZ2h0"
Decoder decoder = Base64.getDecoder();
byte[] decodedByte = decoder.decode(encodedString);
String decodedString = new String(decodedByte);
System.out.println(decodedString); // Outputs: "Highlight"
We have used Base64 class of java.util class, it is available since JDK 1.8 . Base64 class has both encoder and decoder method.
Now lets take another example in java to save base64 image data.
/***** Decoding Base64 Image In Java ******/
String partSeparator = ",";
if (imageBase64.contains(partSeparator)) {
String encodedImg = imageBase64.split(partSeparator)[1];
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
InputStream in = new ByteArrayInputStream(decodedImg);
String updatedFileName = UUID.randomUUID().toString() + ".png";
BufferedImage ImageFromConvert = ImageIO.read( in );
File profilePicUrl = new File(profileImageLocation + "/" + updatedFileName);
ImageIO.write(ImageFromConvert, "png", profilePicUrl); in .close();
}
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
S. Ajit
Ajit is a software developer who loves solving problems and programming in C, C++, Java. He also has a passion to learn new technologies.