【发布时间】:2011-03-26 09:12:02
【问题描述】:
我以字符串格式对图像进行 base64 编码。需要将其压缩/调整大小为不同大小,即从这些压缩/调整大小的 base64 编码图像创建的图像文件大小不同。
Java 中可以使用哪些压缩/调整大小算法/jar?
【问题讨论】:
标签: compression image-manipulation base64
我以字符串格式对图像进行 base64 编码。需要将其压缩/调整大小为不同大小,即从这些压缩/调整大小的 base64 编码图像创建的图像文件大小不同。
Java 中可以使用哪些压缩/调整大小算法/jar?
【问题讨论】:
标签: compression image-manipulation base64
压缩的输出几乎总是二进制数据,而不是字符串...此时开始进行 base64 转换毫无意义。
图像通常已经压缩(大多数格式都使用压缩),因此您实际上不会获得太多好处。如果您确实需要字符串格式的数据,您可以尝试首先使用GZipOutputStream等压缩原始二进制数据,然后然后对其进行base64编码,但我怀疑你会节省很多空间。
【讨论】:
我正在使用这个函数来返回一个 0.7 大小的图像。 (这是从 Selenium 返回的屏幕截图......如果我把它缩小得太远,图像开始看起来很糟糕。):
public String SeventyPercentBase64(String in_image)
{
String imageData = in_image;
//convert the image data String to a byte[]
byte[] dta = DatatypeConverter.parseBase64Binary(imageData);
try (InputStream in = new ByteArrayInputStream(dta);) {
BufferedImage fullSize = ImageIO.read(in);
// Create a new image .7 the size of the original image
double newheight_db = fullSize.getHeight() * .7;
double newwidth_db = fullSize.getWidth() * .7;
int newheight = (int)newheight_db;
int newwidth = (int)newwidth_db;
BufferedImage resized = new BufferedImage(newwidth, newheight, BufferedImage.SCALE_REPLICATE);
Graphics2D g2 = (Graphics2D) resized.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//draw fullsize image to resized image
g2.drawImage(fullSize, 0, 0, newwidth, newheight, null);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write( resized, "png", baos );
baos.flush();
byte[] resizedInByte = baos.toByteArray();
Base64Encoder enc_resized = new Base64Encoder();
String out_image = enc_resized.encode(resizedInByte);
return out_image;
}
} catch (IOException e) {
System.out.println("error resizing screenshot" + e.toString());
return "";
}
}
【讨论】: