java图片编码解码

目录

图片编码

前端展示

图片解码

其他


图片编码

获取图片的二进制byte[]数组,然后base64编码,这样是为了给前端返回展示。

        BASE64Encoder encoder = new sun.misc.BASE64Encoder();

        File f = new File("F:\\Temp\\test.png");
        BufferedImage bi;
        bi = ImageIO.read(f);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, "png", baos);
        byte[] bytes = baos.toByteArray();

        String base64Str = encoder.encodeBuffer(bytes).trim();

 如下就是base64Str的部分样子,

/9j/4AAQSkZJRgABAAAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAAB//8AAKACAAQAAAABAAAAZKADAAQAAAABAAAAjAAAAAD//gAgSnBlZyBDb2RlYyB8IGZsdXhjYXBhY2l0eS5uZXQg/9sAhAADAgIDAgIDAwMDBAMDBAUIBQUEBAUKBwcGCAwKDAwLCgsLDQ4SEA0OEQ4LCxAWEBETFBUVFQwPFxgWFBgSFBUUAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCACMAGQDAREAAhEBAxEB/8QBogAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoLEAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+foBAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKCxEAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYG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/tB8eKtP/AOvIf+hvXPUYXPXSwJzXSMjY84oEyvJgDrQYnyT/AMFEPGMul/Dbw/4

前端展示

返回了base64Str后,需要在前端展示,下面是vue的代码,获取后台的base64Str,直接前端展示。

 let base64Str = "data:image/png;base64,"+res.data;
 this.imgSrc = base64Str;

 <image :src="imgSrc" style="border-radius:50%;width:400rpx;height:400rpx"></image>

图片解码

  解码并写回到系统盘。

BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        byte[] bytes1 = decoder.decodeBuffer(base64String);

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
        BufferedImage bi1 = ImageIO.read(bais);
        File w2 = new File("F:\\Temp\\test2.png");//可以是jpg,png,gif格式
        ImageIO.write(bi1, "png", w2);//不管输出什么格式图片,此处不需改动
    

其他

其实如果光光是图片展示的话,还可以使用HttpServletResponse流直接写出byte[]数组。

图片的byte数组其实就  [102,103,104,22,-2,332......] 这样的格式。

@RequestMapping("getPhoto")
public byte[] getPhoto(HttpServletResponse response){
    byte[] bytes = //图片的二进制流数据

    ServletOutputStream os = response.getOutputStream();
    os.write(bytes);
    os.flush();
}

浏览器直接访问就能展示图片,所以直接在image标签中加上这个url就行。

<image src="http://192.168.3.92:8088/api/photo/getPhoto"></image>

 

posted @ 2022-03-24 17:01  伟衙内  阅读(301)  评论(0编辑  收藏  举报