Writing .jpg files

I use the following line for writing Image files:

/**Saves the specified image to file.
 * @param image the Image to save
 * @param extension the extension of the file type to write
 * @param file the file to write to
 */
ImageIO.write(image, extension, file);

If the extension is png, it works fine. If the extension is jpg, the file is discolored. I realize that jpeg is a lossy format, but the resulting files are ridiculously discolored. Is this a bug in ImageIO, or do I need to do something special?

I’m using version 1.5 update 9.

It should be 75 or 80% jpeg with 2x2 luminance cells. Depending on the image it should either look ok or well, shit (if there are few colors, hard edges, strong contrasts etc - png would have been a better choice then).

Feel free to post the images (png and jpeg).

There is also another way to write jpegs with some control about the compression. Cant remember how its done… never really wanted to write jpegs myself.

Try this :


class JPEGWriter
			{
	static float quality=0.9f; // <---THIS MIGHT BE YOUR PROBLEM
	public static void write(BufferedImage img,File filename)
					{
			try
			   {
			   	FileOutputStream out=new FileOutputStream(filename);
			   	JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
			   	JPEGEncodeParam jep=encoder.getDefaultJPEGEncodeParam(img);
			   	jep.setQuality(quality,false);
			   	
			   	encoder.setJPEGEncodeParam(jep);
			   	encoder.encode(img);
			   	
			    out.close();
			   }
			   catch(Exception e)
			   			{
			   			e.printStackTrace();	
			   			}	
					}			
				
				
			}	

and use this like that :


new JPEGWriter().write(imag,file);

imag is a BufferedImage and file is the file you want to create.
This should work…

I tried the code in the JPEGWriter class, and the same thing happened. I even tried setting the quality to 1.0f, but it made no difference.

I’m attaching the different images - one encoded as a .png and one encoded as a .jpg.

Hm. Looks totally garbled. Try copying it over to some opaque image before saving. No idea if that helps tho.

Copying the image to an opaque image first did the trick. Using the contents of class JPEGWriter is unnecesary.

Please read the evaluation of this bug report:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4836466

In short, it’s a limitation in other native apps, not in Java.

Chris