When I set the setRGB value, getRGB returns a different value. What for?

Why here I am setting RGB () with three RGB colors (125, 126, 127), but when getRGB returns a different value (125, 126, 128). For (122, 126, 127) it returns true (122, 126, 127). What for? And also: Input: image.setRGB (0, 0, 5072962) // 77 ----- 104 ----- 66 ------- 5072962 Output: 78 ------ 104 - ---- 69 ------- 5138501 ( rgb = (red <16) | (green <8) | blue;)

My code:

// 77 ------- 104 ------- 66 ------ 5072962

final static int rgb = 5072962;

public static void main(String[] args) {

    BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);

    //image.setRGB(0, 0, 5072962);
    Color c = new Color(125, 126, 127);
    image.setRGB(0, 0, c.getRGB());

    File outputFile = new File("123.jpg");
    try {
        ImageIO.write(image, "jpg", outputFile);
        File f = new File("123.jpg");
        BufferedImage bi = ImageIO.read(f);
        for (int h = 0; h < 1; h++) {
            for (int w = 0; w < 1; w++) {
                int pixel = bi.getRGB(w, h);
                Color c2 = new Color(pixel);

                int red = c2.getRed();
                int green = c2.getGreen();
                int blue = c2.getBlue();

                int rgb = (red << 16) | (green << 8) | blue;
                System.out.printf("%-8d%-8d%-8d%-8d", red, green, blue, rgb);
                System.out.println("");
            }
        }
    } catch (IOException ex) {
        System.out.println("Error output File image!");
    }

}

      

+3


source to share


1 answer


Did you know about image file formats first? I have the same problem in a similar case. I would like to offer you the following.

When you use jpg

for a write operation an image for storage in your storage, the values RGB

change slightly because the format jpg

is the compressed compressed file format. This compression allows you to save optimal storage space for the file, but it does not store the information about the values RGB

you want.



So, if the file format is not a big problem for you, then just use the format PNG

. Format PNG

is a lossless compression format so you can get the values RGB

you specified earlier in the program.

Hope this helps you.

+2


source







All Articles