问题描述
我正在尝试读取流并将读取的图像保存到zip文件中,因为这将在多天内运行并生成太多单个文件。
I am attempting to read in a stream and save the read images to a zip file as this is going to be running over multiple days and would generate far too many individual files.
我现在遇到一个问题,我似乎无法将图像保存到zip文件中。我为它构建的工作线程如下。我确信图像正在进入ImageIO.write。最后的结果是一个空的jpgs的zip文件。我想知道ImageIO是否没有将属性写入ZipOutputStream。
I now have an issue where I seem to be unable to save images into a zip file. The worker thread I have built for it is below. I am sure that the image is making it to the ImageIO.write. The result at the end however is a zip file of empty jpgs. I am wondering if perhaps ImageIO is not writing property to the ZipOutputStream.
感谢您的帮助。
public class ZipSaveWorker implements Runnable{
public static ZipOutputStream out=null;
BufferedImage myImage;
private static int counter=0;
public void run() {
ZipEntry entry=new ZipEntry("video"+counter+".jpg");
counter++;
try {
out.putNextEntry(entry);
ImageIO.write(myImage, ".jpg", out);
} catch (IOException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ZipSaveWorker(BufferedImage image)
{
if (out==null)
{
try {
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File("images" + File.separator + "video.zip"))));
} catch (FileNotFoundException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
counter=0;
}
myImage=image;
}
public static void closeStream()
{
try {
out.flush();
out.close();
} catch (IOException ex) {
Logger.getLogger(ZipSaveWorker.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
推荐答案
您的代码中的错误在以下行中:
The error in your code is in the line:
ImageIO.write(myImage, ".jpg", out);
它应该是:
ImageIO.write(myImage, "jpg", out);
我也不确定你是否应该在每个图像写完后调用closeEntry()。
I am also not sure if you should call closeEntry() after every image has been written.
考虑一下Stephen C写的内容,如果电源被切断或VM死机,此代码可能会导致损坏的zip文件。考虑每周对zip文件进行几次备份,甚至每天几次,以确保您的多天运行不会完全毁掉(我假设可以恢复运行)。
Consider what Stephen C writes, this code could result in corrupt zip files if the power was cut or the VM died. Consider making backups of the zip files a few times a week, maybe even a few times a day, to ensure your multiple day runs aren't completely ruined (I assume a run can be resumed).
这篇关于如何将图像保存为zip文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!