我看过several examples通过写入文件从Java BufferedImage
对象制作压缩的JPG图像,但是可以在不写入文件的情况下执行JPG压缩吗?也许写信给ByteArrayOutputStream
ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpgWriteParam.setCompressionQuality(0.7f);
ImageOutputStream outputStream = createOutputStream();
jpgWriter.setOutput(outputStream);
IIOImage outputImage = new IIOImage(image, null, null);
// in this example, the JPG is written to file...
// jpgWriter.write(null, outputImage, jpgWriteParam);
// jpgWriter.dispose();
// ...but I want to compress without saving, such as
ByteArrayOutputStream compressed = ???
?
reducers/index.js
答案 0 :(得分:9)
只需将 ByteArrayOutputStream
传递给 ImageIO.createImageOutputStream(...)
,如下所示:
//重要部分:创建内存流
 ByteArrayOutputStream compressed = new ByteArrayOutputStream();
 ImageOutputStream outputStream = ImageIO.createImageOutputStream(压缩);

 //注意:其余的代码只是代码的清理版本

 //获取JPEG格式的编写器
 ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName(“jpg”)。next();
 
 //配置JPEG压缩:70%质量
 ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
 jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
 jpgWriteParam.setCompressionQuality(0.7f); 

 //将内存中的流设置为输出
 jpgWriter.setOutput(outputStream);

 //将图像写为JPEG w /已配置的设置为in -memory stream
 //(IIOImage只是一个聚合对象,al让你将
 //缩略图和元数据关联到图像,它“什么都不做”
 jpgWriter.write(null,new IIOImage(image,null,null),jpgWriteParam);
& #xA; //将编写器设置为释放资源
 jpgWriter.dispose();

 //获取数据以便进一步处理...
 byte [] jpegData = compressed.toByteArray ();



 PS:默认情况下, ImageIO
将在创建 ImageOutputStream时使用磁盘缓存代码>。这可能会减慢内存中的流写入速度。要禁用它,请使用
ImageIO.setCache(false)
(全局禁用磁盘缓存)或显式创建 MemoryCacheImageOutputStream
(本地),如下所示:
ImageOutputStream outputStream = new MemoryCacheImageOutputStream(compressed);