Java将图片进行Base64编码和解码

新逸网络 2.2K 0

 

DataURI 允许在HTML文档中嵌入小文件,可以使用img标签或CSS嵌入转换后的Base64编码,减少HTTP请求,加快小图像的加载时间。 经过Base64编码后的文件体积一般比源文件大30%左右。

Base64编解码工具

/**
 * 将网络图片进行Base64编码
 * 
 * @param imageUrl
 * @param formatName
 * @return
 */
public static String encodeImgageToBase64(URL imageUrl, String formatName) {
	ByteArrayOutputStream outputStream = null;
	try {
		BufferedImage bufferedImage = ImageIO.read(imageUrl);
		outputStream = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, formatName, outputStream);
	} catch (MalformedURLException e1) {
		e1.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	// 对字节数组Base64编码
	BASE64Encoder encoder = new BASE64Encoder();
	// 返回Base64编码过的字节数组字符串
	return encoder.encode(outputStream.toByteArray());
}

/**
 * 将本地图片进行Base64编码
 * 
 * @param imageFile
 * @param formatName
 * @return
 */
public static String encodeImgageToBase64(File imageFile, String formatName) {
	ByteArrayOutputStream outputStream = null;
	try {
		BufferedImage bufferedImage = ImageIO.read(imageFile);
		outputStream = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, formatName, outputStream);
	} catch (MalformedURLException e1) {
		e1.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	// 对字节数组Base64编码
	BASE64Encoder encoder = new BASE64Encoder();
	// 返回Base64编码过的字节数组字符串
	return encoder.encode(outputStream.toByteArray());
}

/**
 * 将Base64编码的图片进行解码,并保存到指定目录
 * 
 * @param base64
 * @param path
 * @param imgName
 */
public static void decodeBase64ToImage(String base64, String path, String imgName) {
	BASE64Decoder decoder = new BASE64Decoder();
	try {
		FileOutputStream write = new FileOutputStream(new File(path + imgName));
		byte[] decoderBytes = decoder.decodeBuffer(base64);
		write.write(decoderBytes);
		write.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

使用方法

/* 在CSS中使用 */
.box {
    background-image: url("data:image/jpg;base64,/9j/4QMZR...");
}
<!-- 在HTML中使用 -->
<imgsrc="data:image/jpg;base64,/9j/4QMZR..."/>

优缺点

  • 使用base64图片的优点有:
    1、减少http请求次数
    2、采用base64的图片随着页面一起下载,因此不会存在跨域请求的问题
    3、没有图片更新要上传图片,因此不会造成清理图片缓存的问题
  • 使用base64图片的缺点:
    1、增加css文件的大小
    2、浏览器兼容性
    3、解析css的时间增长

本文链接:https://www.xinac.com/article/586.html

原文链接:https://blog.xinac.cn/archives/java-base64.html


 

发表评论 取消回复
表情 图片 链接 代码

分享