0

I wrote an image with this code:

BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
index = 0;

for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {

        int r = ciphered[index++];
        int g = ciphered[index++];
        int b = ciphered[index++];

        Color newColor = new Color(r, g, b);
        newImage.setRGB(j, i, newColor.getRGB());
    }
}
File ouptut = new File("/Users/newbie/Desktop/encrypted.jpg");
ImageIO.write(newImage, "jpg", ouptut);

When I try to read the image ("encrypted.jpg") I get different RGB values. I read the image with the following code:

File input = new File("/Users/newbie/Desktop/encrypted.jpg");

BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB);
image = ImageIO.read(input);
int[] t = new int[width * height * 3];

for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {

        Color c = new Color(image.getRGB(j, i));

        int r = c.getRed();
        int g = c.getGreen();
        int b = c.getBlue();

        t[index++] = r;
        t[index++] = g;
        t[index++] = b;
    }
}

I don't understand what I'm doing wrong. I just get different rgb values from the ones I've inserted.

4
  • 3
    JPEG is a lossy compression, this means that the pixel data may be modified to allow for a better compression Commented Feb 20, 2018 at 22:39
  • Thank you. I get it, so is there any way I could save the picture in raw? I need the rgb values to be the ones I want. Commented Feb 21, 2018 at 5:50
  • Sure, I've saved the pixel data (ints) to a text field and used the inbuilt zip support to compress it, it's nothing like png or jpg, but it can work Commented Feb 21, 2018 at 5:52
  • This is a slightly sideways example, I'd personally write the byte information directly out through a ZipOutputStream to a file, but you get the basic idea. You should also try using png of jpg, as it uses a lossless compression and would safe you a considerable amount of time and effort Commented Feb 21, 2018 at 6:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.