【发布时间】:2017-01-28 21:54:53
【问题描述】:
我的应用程序下载 Facebook 用户的 jpeg 个人资料图片,并对其进行 base64 编码。解码时,生成的 jpeg 质量和大小会显着降低。我该如何避免这种情况?
这是我下载/编码的方式:
// Download the profile picture.
BufferedImage image = ImageIO.read(new URL("http://facebook-profile-pic"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", bos);
// Base64 encode it.
String imageData = new String(Base64.getEncoder().encode(bos.toByteArray()));
当我获取 imageData 的值并对其进行解码时,图像比原始下载 URL 处的图像小很多。
【问题讨论】:
-
new String(byteArray)是不可靠的,因为它使用底层系统的默认字符集来编码字节。如果该字符集是 UTF-8 或某些 ISO-8859 字符集,它将适用于 Base64 编码的字节,但如果是其他字符集,您的数据将被损坏。请改用String imageData = Base64.getEncoder().encodeToString(bos.toByteArray());。 -
JPEG 是一种无损文件格式,ImageIO 在写入时使用特定的质量。为了获得更高的质量和/或无损,您需要明确指定质量
标签: java compression base64 jpeg loss