try { BufferedImage bi = null; if (isURL == true) { bi = ImageIO.read(new URL(inFileName)); } else { bi = ImageIO.read(new File(inFileName)); } int[] rgbArray = new int[101 * 29];//我测试用的图象文件象素值宽度是101宽,29长的 bi.getRGB(0, 0, 101, 29, rgbArray, 0, 101); for (int i = 0; i < 101 * 29; i++) {//我做的只是双色图,所以这里查出每一个象素是1(黑)还是0(白) if ((rgbArray[i] & 0xffffff) == 0x000000) rgbArray[i] = 0; else rgbArray[i] = 1; } //以下是BMP文件格式的定义,更加具体的说明可以到找 int[] identifier = { @#B@#, @#M@# }; int[] fileSize = { 0x0E, 0x02, 0x00, 0x00 }; int[] reserved = { 0x00, 0x00, 0x00, 0x00 }; int[] bitmapDataOffset = { 0x3E, 0x00, 0x00, 0x00 }; int[] bitmapHeaderSize = { 0x28, 0x00, 0x00, 0x00 }; int[] width = { 0x65, 0x00, 0x00, 0x00 }; int[] height = { 0x1D, 0x00, 0x00, 0x00 }; int[] planes = { 0x01, 0x00 }; int[] bitsPerPixel = { 0x01, 0x00 }; int[] compression = { 0x00, 0x00, 0x00, 0x00 }; int[] bitmapDataSize = { 0xD0, 0x01, 0x00, 0x00 }; int[] hResolution = { 0x00, 0x00, 0x00, 0x00 }; int[] vResolution = { 0x00, 0x00, 0x00, 0x00 }; int[] colors = { 0x00, 0x00, 0x00, 0x00 }; int[] importantColors = { 0x00, 0x00, 0x00, 0x00 }; int[] palette = { 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00 }; //记住bmp没一个扫描行都要扩充到下一个4bytes的倍数,如101就要变成128,扩充的byte补0即可 int[] bitmapData = new int[(101 + 27) * 29 / 8]; int n = 0; for (int i = 0; i < 29; i++) { //BMP格式是从最后一行开始scan的 for (int j = 1; j <= 101; j++) { if (rgbArray[(28 - i) * 101 + j - 1] == 1) { bitmapData[n] = bitmapData[n] | (1 << (8 - j % 8) % 8); } if (j % 8 == 0) { n++; } if (j == 101) { n += 4; } } } RandomAccessFile o = new RandomAccessFile(outFileName, "rw"); o.setLength(0); for (int i = 0; i < identifier.length; i++) { o.write(identifier[i]); } for (int i = 0; i < fileSize.length; i++) { o.write(fileSize[i]); } for (int i = 0; i < reserved.length; i++) { o.write(reserved[i]); } for (int i = 0; i < bitmapDataOffset.length; i++) { o.write(bitmapDataOffset[i]); } for (int i = 0; i < bitmapHeaderSize.length; i++) { o.write(bitmapHeaderSize[i]); } for (int i = 0; i < width.length; i++) { o.write(width[i]); } for (int i = 0; i < height.length; i++) { o.write(height[i]); } for (int i = 0; i < planes.length; i++) { o.write(planes[i]); } for (int i = 0; i < bitsPerPixel.length; i++) { o.write(bitsPerPixel[i]); } for (int i = 0; i < compression.length; i++) { o.write(compression[i]); } for (int i = 0; i < bitmapDataSize.length; i++) { o.write(bitmapDataSize[i]); } for (int i = 0; i < hResolution.length; i++) { o.write(hResolution[i]); } for (int i = 0; i < vResolution.length; i++) { o.write(vResolution[i]); } for (int i = 0; i < colors.length; i++) { o.write(colors[i]); } for (int i = 0; i < importantColors.length; i++) { o.write(importantColors[i]); } for (int i = 0; i < palette.length; i++) { o.write(palette[i]); } for (int i = 0; i < bitmapData.length; i++) { o.write(bitmapData[i]); } o.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
|