简体   繁体   English

当我设置setRGB的值时,getRGB返回不同的值。 为什么?

[英]When I set a value of setRGB, getRGB returns a different value. Why?

Why here I setRGB () with three RGB colors (125, 126, 127), but when getRGB it returns another value that is (125, 126, 128). 为什么在这里我用三种RGB颜色(125,126,127)设置RGB(),但是当getRGB它返回另一个值(125,126,128)。 For (122, 126, 127), it returns true (122, 126, 127). 对于(122,126,127),它返回true(122,126,127)。 Why? 为什么? And: Input: image.setRGB (0, 0, 5072962) // 77 ----- 104 ----- 66 ------- 5072962 Output: 78 ------ 104 ------ 69 ------- 5138501 (With rgb = (red << 16) | (green << 8) | blue;) 并且:输入:image.setRGB(0,0,5072962)// 77 ----- 104 ----- 66 ------- 5072962输出:78 ------ 104 --- --- 69 ------- 5138501(用rgb =(红色<< 16)|(绿色<< 8)|蓝色;)

My code: 我的代码:

// 77-------104-------66------5072962 // 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!");
    }

}

At first, Did you Know about Image file formats ? 首先,你知道图像文件格式吗? I have the same problem before in similar case. 在类似的情况下,我有同样的问题。 I would like to suggest you the following. 我想建议你以下。

When you use jpg for the image write operation to store in your storage, RGB values changes slightly because jpg format is a lossy compressed file format. 当您使用jpg进行存储在存储中的图像写入操作时, RGB值会略有变化,因为jpg格式是一种有损压缩文件格式。 This compression allows you for the optimal space to store the file but it doesn't store the information of RGB values you want. 此压缩允许您获得存储文件的最佳空间,但它不会存储您想要的RGB值信息。

So, If file format is not a big issue for you , then simply use PNG format. 因此,如果文件格式对您来说不是一个大问题,那么只需使用PNG格式。 PNG format is a lossless compression file format so that you can retrieve RGB values you have set before in the program. PNG格式是一种无损压缩文件格式,因此您可以检索之前在程序中设置的RGB值。

Hope it might help you. 希望它可以帮到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM