简体   繁体   中英

How to get RGB values using Java

I'm trying to get the pixels in RGB format of an image. I have the following code:

public void writeColorImageValueToFile(BufferedImage in, String fileName)   
    {   
    int width = in.getWidth();   
    int height = in.getHeight();   

    try   
    {   
        FileWriter fstream = new FileWriter(fileName + ".txt");   
        BufferedWriter out = new BufferedWriter(fstream);   

        int [] data = new int[width * height];      
        in.getRGB(0, 0, width, height, data, 0, width);   

        for(int i = 0; i < (height * width); i++)   
        {                        
            out.write(((data[i] >> 16) & 0xff) + ", ");    
            out.write(((data[i] >> 8) & 0xff) + ", ");   
            out.write((data[i] & 0xff) + "\n");   
        }   

        out.close();   
    } catch (Exception e)   
    {   
        System.err.println("Error: " + e.getMessage());   
    }   
}   

I created an image in photoshop and I filled it with the color RGB(86, 136, 152), however I got from my java method the value of RGB(44, 139, 154).

I load the image using:

BufferedImage img = ImageIO.read(new File("blue.jpg"))    

I don't know what I'm doing wrong.

Any suggestion?

尝试将图像保存为PNG格式,然后重试!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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