I'm trying to convert an image file to Base64 string using BufferedImage class. Even though the code is not giving any compilation/run time errors the output is not getting printed in the console.
Eclipse IDE code:
public class BufferImage {
public static void main(String args[]) {
try
{
BufferedImage img = null;
img = ImageIO.read(new File("image.jpg")); // eventually C:\\ImageTest\\pic2.jpg
String image_string = encodeToString(img, "string");
System.out.println(image_string);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static String encodeToString(BufferedImage image, String type)
{
String base64String = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
base64String = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return base64String;
}
}
How to overcome this?
The problem lies in ImageIO.write(image, type, bos);
. In your case type is "String"
, but that is most likely not a valid format. To see all the formats at your disposal execute ImageIO.getReaderFormatNames()
.
If you can use Apache Commons, I suggest you try the following to encode your file to Base64: (fileImage
is of type File
):
byte[] imageBytes = Base64.encode(FileUtils.readFileToByteArray(fileImage));
String base64String = new String(imageBytes);