Posts

Showing posts with the label Working with Images

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 ...