[Java] - Encode/Decode Base64 String
Saturday, July 14, 2018
I. Encode image to base64 string
Convert an image to base64 string so that send via SOAP Message, RESTFul or save to database.
Codes:
public String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
//imageString = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
II. Decode base64 string to image
Decode base64 sring to image so that display on UI or other.
Codes:
private BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
//imageByte = Base64.getDecoder().decode(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
LOGGER.err(e.toString());
return null;
}
return image;
}
Updating...
Bài liên quan
- [Java] - The diferrence ==, equals
- [Java] - Exception & Loging
- [Java Swing] - How to create a Menu Bar in Java UI.
- [Java Design Pattern] - Abstract class
- [Java Design Pattern] - Interface
- Spring + Thymleaf
- [Java] - ORM on Java
- [Java] - Run Java App as a Service in Cent OS
- [Oracle] - JAVA and another one related JAVA
- [Java] - Spring Frame A -> Z
- [Java Core] - hashCode method
- [Java Design Pattern] [Creational Pattern] - Singleton
Comments[ 0 ]
Post a Comment