Java examples for 2D Graphics:Image
Encode image to string
//package com.java2s; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import sun.misc.BASE64Encoder; public class Main { /**/* w w w. ja v a 2 s. c o m*/ * Encode image to string * * @param image * The image to encode * @param formatName jpeg, bmp, ... * @return encoded string * @throws Exception */ public static String encodeToString(BufferedImage image, String formatName) throws Exception { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, formatName, bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { throw new Exception( "Error when try to convert image to bse64.", e); } return imageString; } public static String encodeToString(String pathImage, String formatName) throws Exception { BufferedImage image = null; try { image = ImageIO.read(new File(pathImage)); } catch (IOException e1) { throw new Exception( "Error when try to read image " + pathImage, e1); } return encodeToString(image, formatName); } }