Java封装BufferedImage与base64互转方法

一、BufferedImage转base64 


 
   /**
     * BufferedImage 编码转换为 base64
     * @param bufferedImage
     * @return
     */
    private static String BufferedImageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", bao);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = Base64.encodeBase64(bao.toByteArray());
        String base64 = new String(bytes);
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        System.out.println("值为:" + "data:image/png;base64," + png_base64);
        return "data:image/png;base64," + png_base64;
    }

二、base64转BufferedImage

/**
     * base64 编码转换为 BufferedImage
     * @param base64
     * @return
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        Decoder decoder = Base64.getDecoder();
        try {
            byte[] bytes = decoder.decode(base64);
            ByteArrayInputStream bai = new ByteArrayInputStream(bytes);
            return ImageIO.read(bai);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

你可能感兴趣的:(Java,java)