ImageIO.read() 獲取 BufferedImageBM、文件大小、保留字段、數據偏移量RandomAccessFile 依序寫入所有段// 文件頭
int[] identifier = {'B', 'M'};
int[] fileSize = {0x0E, 0x02, 0x00, 0x00}; // 518 bytes
int[] reserved = {0,0,0,0};
int[] bitmapDataOffset = {0x3E, 0, 0, 0}; // 62 bytes
// 信息頭
int[] bitmapHeaderSize = {0x28, 0, 0, 0}; // 40 bytes
int[] width = {0x65, 0, 0, 0}; // 101
int[] height = {0x1D, 0, 0, 0}; // 29
int[] planes = {0x01, 0};
int[] bitsPerPixel = {0x01, 0};
int[] compression = {0,0,0,0};
int[] bitmapDataSize = {0xD0, 0x01, 0, 0}; // 464 bytes
int[] hResolution = {0,0,0,0};
int[] vResolution = {0,0,0,0};
int[] colors = {0,0,0,0};
int[] importantColors = {0,0,0,0};
// 調色盤:黑(0,0,0) + 白(255,255,255)
int[] palette = {0,0,0,0, 0xFF,0xFF,0xFF,0};
// 像素數據填充邏輯
int[] bitmapData = new int[(101 + 27) * 29 / 8]; // 行填充後總字節數
int n = 0;
for (int i = 0; i < 29; i++) { // 從最後一行開始
for (int j = 1; j <= 101; j++) {
if (rgbArray[(28 - i) * 101 + j - 1] == 1) {
bitmapData[n] |= (1 << (8 - j % 8) % 8);
}
if (j % 8 == 0) n++;
if (j == 101) n += 4; // 行尾填充 4 字節
}
}
(width + 31) / 32 * 4 字節此代碼演示了不依賴外部庫、純手工構建 BMP 文件的完整過程,適合學習圖像文件格式或受限環境下的圖片導出需求。