How to Convert an ImageIcon to a Base64 encoded String in Java

To convert an ImageIcon to a Base64 encoded string, we first need to convert the ImageIcon to a BufferedImage. The BufferedImage then needs to be converted to a ByteArray using a ByteArrayOutputStream. Then using a Base64 encoder, we can convert the ByteArray to a Base64 String.

Particularly useful when trying to save an image loaded into a JLabel  to the database.

To get the image from the JLabel, we need to get the ImageIcon from the JLabel using getIcon();

import com.itextpdf.text.pdf.codec.Base64;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import java.awt.Graphics;

 private String ConvertImageIconToBase64String(ImageIcon ii) {
 // Create a buffered image of the size of the original image icon
 BufferedImage image = new BufferedImage(ii.getIconWidth(),
 ii.getIconHeight(), BufferedImage.TYPE_INT_RGB);

 // Create a graphics object to draw the image 
 Graphics g = image.createGraphics();

 // Paint the icon on to the buffered image
 ii.paintIcon(null, g, 0, 0);
 g.dispose();

 // Convert the buffered image into a byte array
 ByteArrayOutputStream b = new ByteArrayOutputStream();
 try {
 ImageIO.write(image, "jpg", b);
 } catch (Exception ex) {
 // Handle the exception
 }
 byte[] imageInByte = b.toByteArray();

 // Return the Base64 encoded String
 return Base64.encodeBytes(imageInByte);
 }

Comments

Popular posts from this blog

How to install a network Star TSP700II installed on Windows XP in Windows 10

Problems when generating and uploading JSON from CSV for GSTR1