• 0

How to convert a 24-bit RGB bmp to 8-bit grayscale


Question

Ok, so I'm trying to convert an 24-bit colored bitmap to an 8-bit (256 colors) grayscale bitmap.

I am able to convert the bitmap to a 24-bit greyscale (sort of, if you understand what I'm talking about), by using this:

  	FileInputStream file = new FileInputStream(new File(archivo));
  	FileOutputStream gray = new FileOutputStream(new File("gray.bmp"));
  	
  	byte[] header = new byte[54];
  	byte[] data = new byte[921600];
  	
  	file.read(header);
  	file.read(data);

  	byte[] redmatrix = new byte[921600];
  	byte[] greenmatrix = new byte[921600];
  	byte[] bluematrix = new byte[921600];
  	byte[] mix = new byte[921600];


  	int n;

  	for (n=2; n+3 < 921600; n=n+3){
    redmatrix[n] = (byte)(Math.round(((int)data[n-2] + (int)data[n-1] + (int)data[n])/3));
  	}
  	for (n=1; n+3 < 921600; n=n+3){
    greenmatrix[n] = (byte)(Math.round(((int)data[n-1]+(int)data[n]+(int)data[n+1])/3));
  	}
  	for (n=0; n+3 < 921600; n=n+3){
    bluematrix[n] = (byte)(Math.round(((int)data[n]+(int)data[n+1]+(int)data[n+2])/3));
  	}
  	for (n=2; n+3 < 921600; n=n+3){
    mix[n] = redmatrix[n];
  	}
  	for (n=1; n+3 < 921600; n=n+3){
    mix[n] = greenmatrix[n];
  	}
  	for (n=0; n+3 < 921600; n=n+3){
    mix[n] = bluematrix[n];
  	}
  	gray.write(header);
  	gray.write(mix);

  	gray.close();	
  }
  catch (Exception e){
  	System.out.println(e);

I do get a greyscale image, but not the right one.

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.