Compressing TIFF Image
807591May 12 2008 — edited May 12 2008Hi guys,
Am trying to convert images on a folder to an TIFF format, It's working but the size of TIFF is too high. I have tried to compress the tiff using JAI encoder, still it's not working. Any body help me to reduce or compress the TIFF size on this please.
class imageFolder
{
private static ImageEncoder enc = null;
public boolean createTiffImage(String Foldername)
{
try
{
File dir = new File(Foldername);
String[] children = dir.list();
if (children == null)
{
System.out.println("No Images");
return false;
}
else if (children.length == 0)
{
System.out.println("No Images");
return false;
}
else
{
ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("tiff");
if (iter.hasNext())
{
writer = (ImageWriter)iter.next();
}
ImageOutputStream ios = ImageIO.createImageOutputStream(new File(Foldername+"ParentFile.tiff"));
writer.setOutput(ios);
FileInputStream ins = new FileInputStream(Foldername+children[0]);
BufferedImage img = ImageIO.read(ins);
ByteArrayOutputStream out = new ByteArrayOutputStream();
TIFFEncodeParam param = new TIFFEncodeParam();
param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
ImageEncoder tiffEncoder = ImageCodec.createImageEncoder("TIFF",out, param);
tiffEncoder.encode(img);
System.out.println("File is created in the folder " + Foldername);
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
tiffWriteParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
Graphics2D big = img.createGraphics();
big.setFont(new Font("Dialog", Font.PLAIN, 10));
big.setColor(Color.red);
//big.drawString("", 4, 12);
big.drawString("Sample Number", 4, 12);
writer.write(new IIOImage(img, null, null));
for (int i=1; i<=children.length; i++)
{
System.out.println(children.length);
ins = new FileInputStream(Foldername+children);
img = ImageIO.read(ins);
big = img.createGraphics();
big.setFont(new Font("Dialog", Font.PLAIN, 10));
big.setColor(Color.red);
big.drawString("", 4, 12);
big.drawString("Sample Number", 4, 12);
writer.writeInsert(i, new IIOImage(img, null, null), null);
}
encodeAsTIFF(img,"ParentFile.tiff");
ios.flush();
writer.dispose();
ios.close();
return true;
}
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
public static void main(String a[]) throws IOException
{
imageFolder m1 = new imageFolder();
String Foldername="e:/images/";
System.out.println(m1.createTiffImage(Foldername));
}
private static void encodeAsTIFF(BufferedImage bi, String outputFile) {
try {
outputFile = removeLastExt(outputFile)+".tiff";
OutputStream os = new FileOutputStream(outputFile);
TIFFEncodeParam param = new TIFFEncodeParam();
enc = ImageCodec.createImageEncoder("TIFF", os, param);
enc.encode(bi);
os.close();
} catch (IOException e) {
System.out.println("IOException at TIFF encoding..");
System.exit(1);
}
}
private static String removeLastExt(String name) {
int li = name.lastIndexOf(".");
return name.substring(0, li);
}
}