Java 原生支援讀取多種圖片格式,但寫入 BMP 並非強項。本文詳述 24 位元 BMP 檔案結構,並提供完整 BMPFile 類別原始碼,可將 java.awt.Image 物件正確寫入標準 BMP 檔案,適用於需與 Windows 原生應用 (如 Access 報告) 互操作的場景。
bfType="BM"、檔案總大小、保留欄位、資料偏移量 (固定 54)。PixelGrabber 取得 ARGB 像素陣列。pad = (4 - (width * 3) % 4) % 4。intToWord、intToDWord 將整數以 Little-Endian 寫入位元組陣列。private void writeBitmap() {
int pad = 4 - ((biWidth * 3) % 4);
if (pad == 4) pad = 0; // 修正邊界條件
// 從最後一行開始寫入
for (int j = 0; j < size; j++) {
int value = bitmap[rowIndex];
rgb[0] = (byte)(value & 0xFF); // B
rgb[1] = (byte)((value >> 8) & 0xFF); // G
rgb[2] = (byte)((value >> 16) & 0xFF); // R
fo.write(rgb);
// 處理換行與填補...
}
}
此類別填補了 JDK 1.2 之前不支援 BMP 寫入的缺口,即便後續版本支援 JPEG,BMP 仍為 Windows 互操作首選格式。