从imageReader写回修改后的图像

时间:2015-04-14 10:26:03

标签: java file-io bufferedimage javax.imageio

我从动画gif中读取分离的图像,我只需要在frames[i]中对它们进行更改,然后将它们设置回文件并以编辑器的形式保存为新文件。

    File file = new File("gif1.gif");
    ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
    ImageInputStream in = ImageIO.createImageInputStream(file);
    reader.setInput(in);

    File output = new File("k.gif");

    ImageWriter writer = ImageIO.getImageWritersBySuffix("GIF").next();
    ImageOutputStream out = ImageIO.createImageOutputStream(file);
    writer.setOutput(out);

    int numImages = reader.getNumImages(true); 
    BufferedImage[] frames = new BufferedImage[pocetObrazku];

    for (int i = 0; i < numImages; i++)
    {

        BufferedImage image = reader.read(i);
        frames[i] = reader.read(i);        
    }    

我会很高兴得到任何帮助。

1 个答案:

答案 0 :(得分:2)

坦克@StanislavL在评论中链接(https://community.oracle.com/thread/1264385),这真的很有帮助。有我的解决方案:

File file = new File("gif1.gif");
ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
ImageInputStream in = ImageIO.createImageInputStream(file);
reader.setInput(in);

int numImages = reader.getNumImages(true); 
BufferedImage[] frames = new BufferedImage[pocetObrazku];

File fileOut = new File("k.gif");
fileOut.createNewFile();
ImageWriter iw = ImageIO.getImageWritersByFormatName("gif").next();

ImageOutputStream ios = ImageIO.createImageOutputStream(fileOut);
iw.setOutput(ios);
iw.prepareWriteSequence(null);

for (int i = 0; i < numImages ; i++) {
    BufferedImage image = reader.read(i);
    frames[i] = reader.read(i);

    IIOMetadata metadata = reader.getImageMetadata(i);    
    IIOImage ii = new IIOImage(image, null, metadata);      
    iw.writeToSequence(ii, (ImageWriteParam) null);    
}