Write a TIFF in Java
At time of writing the documentation for the Java Image I/O API is a bit sparse, particularily when it comes to file types other than JPG, PNG or GIF.
Although the API is actually incredible easy to use, it took me a couple of hours to find a straightforward way of writing a compressed TIFF that actually worked. I use "PackBits" because it was the only kind of compression that produced a usable TIFF in the application I was targetting (Freehand). Here is my code. Sorry about the lack of indentation. You can download the snippet. Use freely at your own risk.
protected boolean saveTiff(String filename, BufferedImage image) {
File tiffFile = new File(filename);
ImageOutputStream ios = null;
ImageWriter writer = null;
try {
// find an appropriate writer
Iterator it = ImageIO.getImageWritersByFormatName("TIF");
if (it.hasNext()) {
writer = (ImageWriter)it.next();
} else {
return false;
}
// setup writer
ios = ImageIO.createImageOutputStream(tiffFile);
writer.setOutput(ios);
TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.ENGLISH);
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// see writeParam.getCompressionTypes() for available compression type strings
writeParam.setCompressionType("PackBits");
// convert to an IIOImage
IIOImage iioImage = new IIOImage(image, null, null);
// write it!
writer.write(null, iioImage, writeParam);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
Although the API is actually incredible easy to use, it took me a couple of hours to find a straightforward way of writing a compressed TIFF that actually worked. I use "PackBits" because it was the only kind of compression that produced a usable TIFF in the application I was targetting (Freehand). Here is my code. Sorry about the lack of indentation. You can download the snippet. Use freely at your own risk.
protected boolean saveTiff(String filename, BufferedImage image) {
File tiffFile = new File(filename);
ImageOutputStream ios = null;
ImageWriter writer = null;
try {
// find an appropriate writer
Iterator it = ImageIO.getImageWritersByFormatName("TIF");
if (it.hasNext()) {
writer = (ImageWriter)it.next();
} else {
return false;
}
// setup writer
ios = ImageIO.createImageOutputStream(tiffFile);
writer.setOutput(ios);
TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.ENGLISH);
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
// see writeParam.getCompressionTypes() for available compression type strings
writeParam.setCompressionType("PackBits");
// convert to an IIOImage
IIOImage iioImage = new IIOImage(image, null, null);
// write it!
writer.write(null, iioImage, writeParam);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}