📜  Java DIP-图像压缩技术

📅  最后修改于: 2020-12-14 05:37:49             🧑  作者: Mango


可以通过Java轻松压缩和存储图像。图像压缩涉及将图像转换为jpg并将其存储。

为了压缩图像,我们读取图像并将其转换为BufferedImage对象。

此外,我们从ImageIO类中的getImageWritersByFormatName()方法获得了ImageWriter。在此ImageWriter中,创建一个ImageWriteParam对象。其语法如下-

Iterator list = ImageIO.getImageWritersByFormatName("jpg");
ImageWriteParam obj = writer_From_List.getDefaultWriteParam();

从此ImageWriteParam对象,可以通过调用这两个方法setCompressionMode()setCompressionQuality()来设置压缩。它们的语法如下-

obj.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
obj.setCompressionQuality(0.05f);

setCompressionMode()方法采用Mode_EXPLICIT作为参数。简要描述了其他一些模式-

Sr.No. Modes
1

MODE_DEFAULT

It is a constant value that may be passed into methods to enable that feature for future writes.

2

MODE_DISABLED

It is a constant value that may be passed into methods to disable that feature for future writes.

3

MODE_EXPLICIT

It is a constant value that may be passed into methods to enable that feature for future writes.

除了压缩方法外,ImageWriteParam类还提供其他方法。他们简要描述-

Sr.No. Method & Description
1

canOffsetTiles()

It returns true if the writer can perform tiling with non-zero grid offsets while writing.

2

getBitRate(float quality)

It returns a float indicating an estimate of the number of bits of output data for each bit of input image data at the given quality level.

3

getLocale()

It returns the currently set Locale, or null if only a default Locale is supported.

4

isCompressionLossless()

It returns true if the current compression type provides lossless compression.

5

unsetCompression()

It removes any previous compression type and quality settings.

6

unsetTiling()

It removes any previous tile grid parameters specified by calls to setTiling.

以下示例演示如何使用ImageWriteParam类压缩图像-

import java.io.*;
import java.util.*;
import java.awt.image.*;

import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

class Compression {

   public static void main(String[] args) throws IOException {
   
      File input = new File("digital_image_processing.jpg");
      BufferedImage image = ImageIO.read(input);

      File compressedImageFile = new File("compress.jpg");
      OutputStream os =new FileOutputStream(compressedImageFile);

      Iteratorwriters =  ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();

      ImageOutputStream ios = ImageIO.createImageOutputStream(os);
      writer.setOutput(ios);

      ImageWriteParam param = writer.getDefaultWriteParam();
      
      param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      param.setCompressionQuality(0.05f);
      writer.write(null, new IIOImage(image, null, null), param);
      
      os.close();
      ios.close();
      writer.dispose();
   }
}

输出

当您执行给定的代码时,它将图像digital_image_processing.jpg压缩为等效的压缩图像,然后将其写入名称为compress.jpg的硬盘上。

原始图片

图像压缩技术教程

压缩图像-品质因数-0.05

图像压缩技术教程

压缩图像-品质因数-0.5

图像压缩技术教程