Image to Base64

This post will show how easy it is to transform an image into a Base64 String using Java. We will not get into details of why one would need to do it, we are assuming that you considered that this will increase your image size and that you probably have a good idea that you need to transmit your image using Base64 besides the time to convert and the size increase.

The idea is simple, get your image as a byte array and encode it into a String, no secrets. 


private String toBase64( byte[] imageBytes ) {

   String prefix = "data:" + contentType + ";base64, ";
   return prefix + getEncoder( ).encodeToString( imageBytes );

}

That is all you need in modern JVMs, which make the task of getting an encoder trivial. To make this post a bit more useful lets give this method a bit of context to see how easy its usage can be.

Lets image you are processing a file using a regex pattern, and you are trying to replace Strings with the encoded representation of images using Base64. Of course this is troublesome as the image is now a String and it can have several ambiguous characters that might confuse your algorithm. Lets for instance assume you are using a Matcher to locate where the replacement should happen and to perform this operation.

The following class is an incredibly simple example of a helper that can assist you in this scenario. We are building the image representation by simply providing a MIME type along with the bytes that compose our image. Besides that, we are also extracting its dimensions for later usage.


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.regex.Matcher;

import static java.util.Base64.getEncoder;

public class ImageBase64 {

   private int width;
   private int height;
   private String base64String;
   private final String contentType;

   public ImageBase64( String contentType, byte[] imageBytes) throws IOException {

      this.contentType = contentType;
      base64String = toBase64( imageBytes );

      BufferedImage bufferedImage = ImageIO.read( new ByteArrayInputStream( imageBytes ) );
      width = bufferedImage.getWidth( );
      height = bufferedImage.getHeight( );
   }

   public double getHeightCm( int dpi ) {

      return pixelToCentimeter( height, dpi );
   }

   public double getWidthCm( int dpi ) {

      return pixelToCentimeter( width, dpi );
   }

   @Override
   public String toString( ) {

      return getBase64String( );
   }

   private static double pixelToCentimeter( int pixels, int dpi ) {

      return pixels * 2.54 / dpi;
   }

   private String toBase64( byte[] imageBytes ) {

      String prefix = "data:" + contentType + ";base64, ";
      return Matcher.quoteReplacement( prefix + getEncoder( ).encodeToString( imageBytes ) );
   }

   public String getBase64String( ) {

      return base64String;
   }

   public int getHeight( ) {

      return height;
   }

   public int getWidth( ) {

      return width;
   }
}

Now lets see an snipped that demonstrates the replacement happening.


StringBuffer resultString = new StringBuffer( );

while ( matcher.find( ) ) {
   String imageSrc = matcher.group( addressGroup );

   ImageBase64 image = imageMap.get( imageSrc );

   matcher.appendReplacement( resultString, "$1$2" + "width='" + image.getWidth( ) + "' height='" + image.getHeight( ) + "' $3$4" + image + "$6" + "$7" );
}
matcher.appendTail( resultString );

return resultString.toString( );

Notice that we are using the Base64 inside the Matcher in a loop that searches and replaces, combing this logic with our Matcher friendly ImageBase64 class, which provides escaped Base64 Strings for usage with the Matcher class. 

From the initial method, the only modification we had to do was adding Matcher.quoteReplacement to our first method. It is also worth noticing that the prefix we are setting is for data URLs, used in HTML. We actually simplified this example from an HTML parser to show not only how easy is to build the String representation of images, but also how simple it is to use them - bottom line they are just simple Strings after you encode them.

More Blog Entries

thumbnail

0 Comments