Java实现图片与二进制的互相转换
本文实例为大家分享了Java将图片转二进制再将二进制转成图片,供大家参考,具体内容如下
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
importjavax.imageio.ImageIO;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
publicclassTestImageBinary{
staticBASE64Encoderencoder=newsun.misc.BASE64Encoder();
staticBASE64Decoderdecoder=newsun.misc.BASE64Decoder();
publicstaticvoidmain(String[]args){
System.out.println(getImageBinary());
base64StringToImage(getImageBinary());
}
staticStringgetImageBinary(){
Filef=newFile("c://20090709442.jpg");
BufferedImagebi;
try{
bi=ImageIO.read(f);
ByteArrayOutputStreambaos=newByteArrayOutputStream();
ImageIO.write(bi,"jpg",baos);
byte[]bytes=baos.toByteArray();
returnencoder.encodeBuffer(bytes).trim();
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
staticvoidbase64StringToImage(Stringbase64String){
try{
byte[]bytes1=decoder.decodeBuffer(base64String);
ByteArrayInputStreambais=newByteArrayInputStream(bytes1);
BufferedImagebi1=ImageIO.read(bais);
Filew2=newFile("c://QQ.bmp");//可以是jpg,png,gif格式
ImageIO.write(bi1,"jpg",w2);//不管输出什么格式图片,此处不需改动
}catch(IOExceptione){
e.printStackTrace();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短