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

摘要

使用img标签或css嵌入转换后的Base64编码,可以减少HTTP请求,加快小图像的加载时间。

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.net/8869.html 文章源自新逸网络-https://www.xinac.net/8869.html

weinxin
新逸IT技术
扫一扫关注微信公众号
Admin
  • 本文由 发表于 2020-08-03
  • 转载请注明:https://www.xinac.net/8869.html
评论  0  访客  0
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定