Java将图片转换成二进制,将二进制转换成图片
static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
static File file = new File("f://file//timg.png");
public static void main(String[] args) throws Exception {
getImageBinary();
}
private static void getImageBinary() {
File f = new File("f://file//timg.png");
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", baos);
byte[] bytes = baos.toByteArray();
String str = encoder.encodeBuffer(bytes).trim();
base64StringToImage(str);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void base64StringToImage(String base64String) {
try {
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File("f://files//timg.png");
ImageIO.write(bi1, "jpg", w2);
} catch (IOException e) {
e.printStackTrace();
}
}