您需要确保标题正确。 例如,标头中的文件大小字段需要为4个字节(请参阅: BMP文件格式 )。 要精确地写入正确的字节数,可以使用DataOutputStream 。
您需要反转值的尾数 。 Java是大端,而BMP文件是小端。 (请参见代码中对reverseBytes所有调用)。
您的循环将忽略每一行和最后一行的最后一个字节。
您也将忽略位图跨度。 这些是每行末尾的额外填充字节。 由于示例的宽度为320像素,因此碰巧没有多余的字节,但是要处理奇数大小的宽度,您应该处理这些。
File f = new File("C:/scr/game_name" + LocalDate.now().toString() +".bmp");
try (FileOutputStream fos = new FileOutputStream(f)){
DataOutputStream dos = new DataOutputStream(fos);
int header_size = 14 + 40; // Size of both headers
int width = 320;
int height = 240;
short bpp = 24;
// Calculate the stride
int stride = 4 * ((width * bpp + 31) / 32);
// BITMAPFILEHEADER
dos.writeByte(66); // B
dos.writeByte(77); // M
int fileSize = (stride * height) + header_size;
dos.writeInt(Integer.reverseBytes(fileSize)); // Actual size of entire file
dos.writeShort(0); // Reserved
dos.writeShort(0); // Reserved
dos.writeInt(Integer.reverseBytes(header_size)); // starting address of bitmap image data
// BITMAPINFOHEADER
dos.writeInt(Integer.reverseBytes(40)); // Size of header
dos.writeInt(Integer.reverseBytes(width)); // Width
dos.writeInt(Integer.reverseBytes(height)); // Height
dos.writeShort(Short.reverseBytes((short)1)); // Color planes
dos.writeShort(Short.reverseBytes(bpp)); // BPP
dos.writeInt(0); // Compression method
dos.writeInt(0); // Image size
dos.writeInt(0); // Horizontal res
dos.writeInt(0); // Vertical res
dos.writeInt(0); // Number of colors
dos.writeInt(0); // Important colors
for (int y = height - 1; y >= 0; y--) {
for(int x = 0; x < width; x++) {
dos.writeByte(pixels[x + y * width] & 0xFF); //blue
dos.writeByte((pixels[x + y * width] >> 8) & 0xFF); //green
dos.writeByte((pixels[x + y * width] >> 16) & 0xFF); //red
}
// Add padding bytes
for (int s = width * 3; s < stride; s++) {
dos.writeByte(0);
}
}
fos.close();
}
catch(IOException e) {
e.printStackTrace();
}
从长远来看,您可能会发现一个可以为您完成所有这些工作的第三方库可能会更好。