How to convert a binary image data to a jpg file i

2019-09-22 07:36发布

I am receiving a stream of bits over the Ethernet. I am collecting the bits in a byte[] array in Java(I am collecting them in a byte[] because I think its relevant).The stream is a digitized image where every 10 bits represent a pixel. There are 1280*1024 pixels. Every pixel is represented by 10 bits. Hence,1280*1024*10 = 13107200 bits = 1638400 bytes is the image size.

2条回答
乱世女痞
2楼-- · 2019-09-22 08:00

Here is a method that can take a byte array and "split" it into groups of 10 bit. Each group is saved as an int.

static int[] getPixel(byte[] in) {
  int bits = 0, bitCount = 0, posOut = 0;
  int[] out = new int[(in.length * 8) / 10];
  for(int posIn = 0; posIn < in.length; posIn++) {
    bits = (bits << 8) | (in[posIn] & 0xFF);
    bitCount += 8;
    if(bitCount >= 10) {
      out[posOut++] = (bits >>> (bitCount - 10)) & 0x3FF;
      bitCount -= 10;
    }
  }
  return out;
}
查看更多
爷的心禁止访问
3楼-- · 2019-09-22 08:14

here's the solution - but if the 10 bits represent actually 8 bits with some 'nonsense' in the other two bits its better to cut that like b=b>>2 - if your image is color then it sounds strange but use all 10 bits

int[] pix=new int[1280*1024];
for(i=0; i<pix.length; i++) {
  read next ten bits put then in an int
  int b=read();
  pix[i]=0xff000000|b;
}
BufferedImage bim=new BufferedImage(1280, 1024, BufferedImage.TYPE_INT_RGB);
bim.setRGB(0, 0, 1280, 1024, pix, 0, 1280);
  try {
    ImageIO.write(bim, "jpg", new File(path+".jpg"));
  } catch (IOException ex) { ex.printStackTrace(); }
查看更多
登录 后发表回答