java bmp rgb数组_java - 从RGB整数数组生成位图。 我的尝试怎么了? - 堆栈内存溢出...

您需要确保标题正确。 例如,标头中的文件大小字段需要为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();

}

从长远来看,您可能会发现一个可以为您完成所有这些工作的第三方库可能会更好。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值