Skip to main content

Corrupt jpg created when writing indexed gif to jpg (is this a bug?)

1 reply [Last post]
nsullins
Offline
Joined: 2008-12-08

Hello all, and thanks in advance for any help with this.

In attempting to write(Java 1.5) a gif to jpg the resulting file written to disk is corrupt. The colors are all wrong, should be black and white but is peach and green and the first line in the image file isn't consistent with jpg images. The gif image I am trying to write to jpg is an indexed byte image. Here is my code:

Iterator iter;
iter = ImageIO.getImageWritersByFormatName(JPEG);
ImageWriter writer;
ImageWriteParam iwp = null;
FileImageOutputStream output = new FileImageOutputStream(outputFile);
if (iter.hasNext()) {

writer = (ImageWriter)iter.next();
iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(.85f);
writer.setOutput(output);
IIOImage image = new IIOImage(bImage, null, null);
writer.write(null, image, iwp);
output.close();
writer.dispose();
}

Is this a bug with the ImageIO library? Has anyone seen this behavior before? Any suggestions?

Thanks again.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
nsullins
Offline
Joined: 2008-12-08

I should also add that when I write this input BufferedImage as a png then there are no problems i.e. no corrupted file.

I have added below my work-around code to store as png.

boolean isIndexedByteImage = bImage.getType() == INDEXED_BYTE_IMAGE;
FileImageOutputStream output = new FileImageOutputStream(outputFile);
Iterator iter;
//workaround due to corrupt files written when source type is indexed and output format is jpg
if(isIndexedByteImage){
iter = ImageIO.getImageWritersByFormatName(PNG);
isIndexedByteImage = true;
}else{
iter = ImageIO.getImageWritersByFormatName(JPEG);
}
ImageWriter writer;
ImageWriteParam iwp = null;
if (iter.hasNext()) {

writer = (ImageWriter)iter.next();
//don't set compression quality if png output format
if(!isIndexedByteImage){
iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(IMAGE_QUALITY);
}
writer.setOutput(output);
IIOImage image = new IIOImage(bImage, null, null);
writer.write(null, image, iwp);
output.close();
writer.dispose();
}