我有一个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){}
}
}
答案 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)