Write back modified image from imageReader

2020-04-21 02:21发布

I read separated images from animated gif and I need just make change with them in frames[i] and then set them back to file and save with writer as new file.

    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);        
    }    

I'll be glad for any help.

1条回答
看我几分像从前
2楼-- · 2020-04-21 03:04

Tanks @StanislavL for link (https://community.oracle.com/thread/1264385) in comment, it was really helpful. There is my solution:

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);    
}
查看更多
登录 后发表回答