使用ImageIO进行图片和base64String的转换

图片转换base64String

String path="/work/111.png";
        File file=new File(path);
        BufferedImage bufferedImage=null;
        try {
            //图片转base64
            bufferedImage=ImageIO.read(file) ;
            ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
            byte[] bytes=outputStream.toByteArray();
            String base64String=Base64.encodeBase64String(bytes);
            System.out.println(base64String);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

base64String转换图片:

try {
            //base64转图片
            byte[] bytes2=Base64.decodeBase64(base64String);
            ByteArrayInputStream inputStream=new ByteArrayInputStream(bytes2);
            BufferedImage bufferedImage2=ImageIO.read(inputStream);
            ImageIO.write(bufferedImage2,"png",new File("/work/666666.png"));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

 

你可能感兴趣的:(java基础)