保存缓冲图像的压缩率较低

时间:2017-03-24 10:32:11

标签: java

我有一个java程序,它使用java Robot类定期捕获屏幕截图。但由于它经常拍摄屏幕截图(~5秒),它很快就能填满我的硬盘。 有什么方法可以在保存之前减小图像的大小,但可以在不损失质量的情况下重新生成原始图像。

import java.io.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.awt.*;
import com.mysql.jdbc.exceptions.jdbc4.CommunicationsException;
import java.sql.*;  
import java.util.*;
import javax.imageio.ImageIO;
class wtd
{
public static BufferedImage getImage()throws Exception
       {
            Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
              Robot robot = new Robot();


               BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, (int) screenDim.getWidth(),(int) screenDim.getHeight()));
               return image;



    }
      public static void main(String args[])throws Exception
    { 
                 long id=0;
                       try{
                           while(true)
                           {
                       BufferedImage originalImage=getImage();

                          ImageIO.write(originalImage, "jpg", new File("D:/"+id+".jpg"));
                                         id++;


                                 }
                   }

               catch(Exception e){}

            }
        }

2 个答案:

答案 0 :(得分:1)

如果你的图像已经被压缩了,那么使用另一种压缩处理将不是很有用:你将节省空间,但不一定需要很多。

如果您的图像没有或几乎没有压缩,您可以使用经典的压缩工具作为zip,允许无损数据压缩。
您有多级压缩,但压缩程度越高,处理时间越长 因此,根据cpu功率,可用的cpu线程数和图像的大小,你应该使用或多或少的压缩级别。

例如,java.util.zip.ZipOutputStream类允许通过调用setLevel(int level)方法创建具有特定压缩级别的zip。
然后,您可以使用java.util.zip.ZipInputStream类来提取存档。

编辑代码示例:

这是一个未经测试的示例,使用javax.imageio.ImageIO.write() JDK 8特定方法,允许将java.awt.image.BufferedImage写入java.io.OutputStream对象:

  // Here is the capture bufferedImage from your application
  BufferedImage screenShot = ...;

  // You create the zip file and you add entry that will store the image
  FileOutputStream fileOut = new FileOutputStream("yourZipFile.zip");
  ZipOutputStream zipOut = new ZipOutputStream(fileOut);
  zipOut.setLevel(9); // 9 is the max level      
  ZipEntry zipEntry = new ZipEntry("screenshot-2017-03-24_12-03-30.jpg");
  zipOut.putNextEntry(zipEntry);

  // you get the bytes from the image 
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  javax.imageio.ImageIO.write(screenShot, "jpg", out);
  byte[] bytes = out.toByteArray();

  // you write the bytes in the zipOutputStream
  zipOut.write(bytes, 0, bytes.length);
  zipOut.close();

答案 1 :(得分:0)

如果您正在寻找无损压缩,可以试试Lepton achieves

  通过预测JPEG块中的系数并将这些预测作为上下文提供给算术编码器,现有JPEG图像节省了22%。 Lepton完美地保留了原始文件。它以每秒5兆字节的速度压缩JPEG文件,并以每秒15兆字节的速度将它们解码回原始位,安全,确定,并且在24兆字节的内存中。