0

I have read most of the questions here, here,bug and others.

One difference is that all the posts talks about the external image being read. However i am creating the jpg image from ImageIO library itself and i am writing that image to a file and reading the same image file however there is difference in pixel value.

here's my code:

     BufferedImage j = new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB);
        Graphics2D jg = j.createGraphics();
        jg.setColor(Color.GREEN);
        jg.fillRect(0, 0, 100, 100);
        jg.dispose();
        File gr = new File("d:/pics/green.jpeg");
        ImageIO.write(j,"jpeg",gr);
        BufferedImage grbr =  ImageIO.read(gr);
        System.out.format("expected:%s\tactual::%s\n", j.getRGB(40,40), grbr.getRGB(40,40));
        System.out.format("expectedG:%s\tactualG::%s", Color.GREEN.getRGB(), grbr.getRGB(40,40));

Output:

expected:-16711936  actual::-16711935
expectedG:-16711936 actualG::-16711935

I read this excerpt from the questions i saw for help as below

All other image loaders assume that the data is YCbCr in that case, except for ImageIO, which assumes that it is RGB when channels 1 and 2 are not subsampled. So, check whether the first 4 bytes are FF D8 FF E1, and if so, whether channels 1 and 2 are subsampled

I read the first few bytes of the green.jpeg after it is written to the file like this as below

FF D8 FF E0 00 10 4A 46 49 46 00

I read about JFIF on wikipedia and found that above sequence is not according to what is mentioned as here. However this is not applicable here because i created a simple RGB type image and not YCbCr type.

So why simple image creating and reading in ImageIO is giving different results? Thanks in advance.

Community
  • 1
  • 1
chebus
  • 762
  • 1
  • 8
  • 26
  • 3
    JPEG is a *lossy* format, no matter how you create or read the image. If you want the exact same values back, you need use a different format, like PNG or TIFF. – Harald K Jan 22 '16 at 10:00
  • 2
    The questions/bug you have linked are about YCbCr encoded EXIF JPEGs (identified by `FF D8 FF E1`) being decoded as RGB, and causing all wrong colors. ImageIO by default writes JFIF JPEGs (identified by `FF D8 FF E0`), and they are decoded correctly. Anyway, you seem to experience only tiny differences in decoded RGB values. This is to be expected when using JPEG compression. – Harald K Jan 22 '16 at 10:12

1 Answers1

0

The gamuts of the RGB and YCbCr colorspaces are different. That's your first change of having changes. There are various steps in the JPEG process that can introduce rounding errors. The quantization process in JPEG changes values.

You're comparison shows very slight changes that are normal with JPEG.

user3344003
  • 20,574
  • 3
  • 26
  • 62