import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; @SuppressWarnings("restriction") public class ImageTest { static BASE64Encoder encoder = new BASE64Encoder(); static BASE64Decoder decoder = new BASE64Decoder(); public static void main(String[] args) { String img_str=image2Binary(); System.out.println(img_str); base64StringToImage(img_str); } static String image2Binary(){ File f = new File("e:/a.gif"); BufferedImage bi; try { bi = ImageIO.read(f); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", baos); byte[] bytes = baos.toByteArray(); return encoder.encodeBuffer(bytes).trim(); } catch (IOException e) { e.printStackTrace(); } return null; } static void base64StringToImage(String base64String){ try { byte[] bytes = decoder.decodeBuffer(base64String); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage bi =ImageIO.read(bais); File file = new File("e:/a.png"); ImageIO.write(bi, "jpg", file); } catch (IOException e) { e.printStackTrace(); } } }