-1

Hi my code is like this

BufferedImage img1=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
for(int r=0; r<w; r++)
{
    for(int c=0; c<h; c++)
    {
        img1.setRGB(0, 0, w, h, data,0,w);
     }
}
ImageIO.write(img1,"jpg", new File("abc.jpg"));

I want to create image of width w and height h..I am having my pixel values in an int array called data(consists of combined rgb values)..ImageIO.write method creates the image but with different pixel values..please help me out..i tried very hardly..but still not getting..

GameDroids
  • 5,584
  • 6
  • 40
  • 59

1 Answers1

2

The reason why is because you're using JPEG compression. JPEG compression is a lossy compression algorithm, so what you have stored in memory will not be the same as you have written to file. Lossy compression allows for high compression ratios, and to mimic or closely resemble what you visually see in the image, but the actual contents will not be the same. They will certainly be similar though.

The only way you can write to an image file and keep the image pixels the same is to use a lossless compression algorithm. Try using PNG instead.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • thank you for your help..i am getting correct value for png image now..but is there any other options for jpg image? – YASHWANTH J Oct 26 '14 at 03:23
  • @YASHWANTHJ - You can reduce the amount of difference by setting the quality of the JPEG compression to 100. http://stackoverflow.com/questions/17108234/setting-jpg-compression-level-with-imageio-in-java . However, this won't solve your problem if you want the exact pixels to be written to file. If you only want to deal with JPEG, you'll have to use JPEG 2000, as it is the lossless version of JPEG. However, the `ImageIO` class does not support this image standard - only PNG and JPEG. You may have to use external libraries if you want to use JPEG 2000. Try https://code.google.com/p/jj2000/ – rayryeng Oct 26 '14 at 04:21
  • thank you..while writing pixel values to image, it takes much time..can we able to reduce it or not.. – YASHWANTH J Oct 28 '14 at 16:02
  • @YASHWANTHJ You just have to call `setRGB` once instead of looping over each element. Look at the `setRGB` documentation carefully: http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#setRGB(int,%20int,%20int,%20int,%20int[],%20int,%20int). Please open another question if you have anything more beyond your unequal pixel question. – rayryeng Oct 28 '14 at 16:05
  • ![this is my original image for encryption][1] ![after decryption i got this image which is flipped][2] [1]: http://i.stack.imgur.com/Rc8Na.jpg [2]: http://i.stack.imgur.com/fsflM.png can i know why this is happening – YASHWANTH J Nov 16 '14 at 04:03
  • why my image is flipped after decryption – YASHWANTH J Nov 16 '14 at 04:03
  • Make another question. – rayryeng Nov 16 '14 at 04:04