四时宝库

程序员的知识宝库

BufferedImage和Base64相互转化

/**

* BufferedImage 编码转换为 base64

* @param bufferedImage

* @return

*/

public static String BufferedImageToBase64(BufferedImage bufferedImage,String imageFormat) {

ByteArrayOutputStream baos = new ByteArrayOutputStream();//io

try {

ImageIO.write(bufferedImage, imageFormat, baos);//写入流中

} catch (IOException e) {

e.printStackTrace();

}

byte[] bytes = baos.toByteArray();//转换成字节

String base64 = Base64.encode(bytes).trim();//转换成base64串

base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n

return "data:image/jpg;base64," + base64;

}


/**

* base64 编码转换为 BufferedImage

* @param base64

* @return

*/

public static BufferedImage base64ToBufferedImage(String base64) {

try {

byte[] bytes = Base64.decode(base64);

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

return ImageIO.read(bais);

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接