CONTENTS | PREV | NEXT

3.4 The ImageWriter Class

Just as we obtained a list of ImageReaders for a particular format using a method from the ImageIO class, we can obtain a list of ImageWriters:
Iterator writers = ImageIO.getImageWritersByFormatName("png");
ImageWriter writer = (ImageWriter)writers.next();

Once an ImageWriter has been obtained, its destination must be set to an ImageOutputStream:
File f = new File("c:\images\myimage.png");
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);

Finally, the image may be written to the output stream:
BufferedImage bi;
writer.write(bi);

3.4.1 Writing Multiple Images

The IIOImage class is use to store references to an image, one or more thumbnail images, and metadata (non-image data) associated with the image. Metadata will be discussed below; for now, we will simply pass null as the value for the metadata-related parameters.

The ImageWriter class contains a write method that creates a new file from an IIOImage, and a writeInsert method that adds an IIOImage to an existing file . By calling the two in sequence a multi-image file may be written:

BufferedImage first_bi, second_bi;
IIOImage first_IIOImage = new IIOImage(first_bi, null, null);
IIOImage second_IIOImage = new IIOImage(second_bi, null, null);
writer.write(null, first_IIOImage, null);
if (writer.canInsertImage(1)) {
        writer.writeInsert(1, second_IIOImage, null);
} else {
        System.err.println("Writer can't append a second image!");
}



CONTENTS | PREV | NEXT

Oracle and/or its affiliates
Java Technology

Copyright © 1993, 2011, Oracle and/or its affiliates. All rights reserved.

Contact Us