您当前的位置: 首页 >  Java

qq_34412985

暂无认证

  • 0浏览

    0关注

    1061博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java实现image和base64互转

qq_34412985 发布时间:2019-07-18 23:02:54 ,浏览量:0

java安装的目录下的jre/lib/rt.jar中有以下两个类实现base64的编码和解码: sun.misc.BASE64Encoder

sun.misc.BASE64Decoder

下面是java实现:

public class Imagebase64 {     static BASE64Encoder encoder = new sun.misc.BASE64Encoder();     static BASE64Decoder decoder = new sun.misc.BASE64Decoder();     public static void main(String[] args) {         System.out.println(getImageBinary()); // image to base64         base64StringToImage(getImageBinary()); // base64 to image     }     static String getImageBinary() {         File f = new File("d://in.jpg");         try {             BufferedImage 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[] bytes1 = decoder.decodeBuffer(base64String);             ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);             BufferedImage bi1 = ImageIO.read(bais);             File f1 = new File("d://out.jpg");             ImageIO.write(bi1, "jpg", f1);         } catch (IOException e) {             e.printStackTrace();         }     } }

关注
打赏
1653291990
查看更多评论
立即登录/注册

微信扫码登录

0.0413s