javaimage-processingmonochrome

Display a gray scale image from a matrix in Java


I'm trying to read a file where a have a Matrix that represent an image monochrome,with BufferedImage in JAVA like that

    final BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g = (Graphics2D)img.getGraphics();
    ... /*reading from file*/ 
    try (InputStream in = new FileInputStream("file.mac");
         Reader reader = new InputStreamReader(in, encoding);
         // buffer for efficiency
         Reader buffer = new BufferedReader(reader)) {
        int r;
        int i=0;
        int j=0;
        while ((r = buffer.read()) != -1) {
             g.setColor(new Color(?,?,?)); 
             g.fillRect(i, j, 1, 1);
             i++;
             if(i==WIDTH){
                 j++;
                 i=0;
             }
       }
    }

the problem is what i will set the color in this line g.setColor(new Color(?,?,?)); that a get in r variable that represent the gray scale level in the matrix.


Solution

  • You will have to set the color parameters, red, green and blue, to the same values to archive a grey color. The Color constructor accepts RGB values between [0, 255], so you will have to scale your r values to match the [0, 255] scale:

    int grey = r/rMax * 255 //Gives you a grey value between [0, 255];
    

    rMax being the biggest r value in your file.

    Then set your color to

    g.setColor(new Color(grey, grey, grey));
    

    To make the whole thing more efficient, I would suggest creating an array of grey colors first to avoid creating a lot of duplicate Color objects:

    Color[] colors = new Color[256];
    
    for (int i = 0; i <=255; i++) {
        colors[i] = new Color(i, i, i);
    }
    

    and then set the Color in your loop to

    g.setColor(colors[grey]);