0

i have following problem: I work with image in java. I set the color pixels and then i save image. But if i load this image to program. Pixels having different color ! Code:

BufferedImage img = loadImage();
.
.
//new image for drawing
BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(),
                BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) newImg.getGraphics();

//get pixel color
int pixel = img.getRGB(0, 0);

//parsing color
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;

//real drawing
g2.setColor(new Color(red, green, blue));
            g2.drawLine(0, 0, 0, 0); // COLOR IS R: 55, G: 54 B: 53

//saving 
ImageIO.write(newImg, "jpg", outputfile);

After this, I run another program which can read pixel color..

The commands are same..

If i check color of new image, rgb are: R 52, G: 48 B: 81.

I set R: 55, G: 53, B:53 And its R 52, G: 48 B: 81

Where can be a problem?

Thank you for your advice.

slearace
  • 31
  • 6
  • 1
    JPG is a lossy encoding. You're setting a single pixel of the image, and JPEG compression probably changes its value. – JB Nizet Apr 25 '15 at 17:43
  • @JBNizet: Can it somehow solve ? Disable compression? – slearace Apr 25 '15 at 17:45
  • Start by confirming this is the problem by setting all the pixels of the image, or by using a lossless encoding like PNG. – JB Nizet Apr 25 '15 at 17:46
  • possible duplicate of [RGB value not change correctly after saving image in JAVA](http://stackoverflow.com/questions/20021568/rgb-value-not-change-correctly-after-saving-image-in-java) – Harald K Apr 25 '15 at 18:22

1 Answers1

2

this is because of Jpeg type

Jpeg values doesn't save discretely but Jpeg save RGB values of picture as a function.

instead of using jpeg use png format and see that setRGB() works exactly.

so replace your code to below

ImageIO.write(image, "png", outputfile);
mmsamiei
  • 165
  • 1
  • 2
  • 10