[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
Comments[ 0 ]
Post a Comment