尝试查找 .bmp 文件的高度和宽度在处理中得到不一致的结果

Guy*_*ael 2 java processing bit-manipulation bmp

我正在尝试手动绘制从 .bmp 文件读取的像素。

该信息存储在 BMP 标头中。图像宽度(4 字节 - 0x12 到 0x15)、图像高度(4 字节 - 0x16 - 0x19)以及原始像素数据的偏移量(4 字节 - 0xa 到 0xd)。为了找到宽度和高度,我使用这个:

byte[] bytes = loadBytes("ImageFile.bmp");
imageWidth =  ((bytes[0x12]) | (bytes[0x13])<<8 | (bytes[0x14])<<16 | (bytes[0x15])<<24) ;
imageHeight = ((bytes[0x16]) | (bytes[0x17])<<8 | (bytes[0x18])<<16 | (bytes[0x19])<<24) ;
offset = (bytes[0xa]) | (bytes[0xb])<<8 | (bytes[0xc])<<16 | (bytes[0xd])<<24;
size(imageWidth,imageHeight);  
Run Code Online (Sandbox Code Playgroud)

之后,我得到准确的结果:imageWidth是600,imageHeight是780。

但对于较小的bmp图像,250x250,经过相同的计算,我得到2的补码的答案:imageWidth是-6,imageHeight是-6。

这种转换对我来说很奇怪,因为当我用记事本++查看十六进制数据时,我得到:

fa 00 00 00 fa 00 00 00  
Run Code Online (Sandbox Code Playgroud)

这些来自 0x12 - 0x19 的字节。它们不存储为有符号值。那么我为什么这样读它们呢?

无论实际大小如何,是否有一种方法可以获取实际的无符号值?

谢谢你!

g00*_*0se 5

请参阅我上面关于以困难的方式做到这一点的评论。这要容易得多:

ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
bb.position(0x12);
int width = bb.getInt();
int height = bb.getInt();
Run Code Online (Sandbox Code Playgroud)

艰辛的道路:

long imageWidth = bytes[0x12] & 0xFF | (bytes[0x13] & 0xFF) << 8 | (bytes[0x14] << 16) & 0xFF | (bytes[0x15] << 24) & 0xFF;
long imageHeight = bytes[0x16] & 0xFF | (bytes[0x17] & 0xFF) << 8 | (bytes[0x18] & 0xFF) << 16 | (bytes[0x19] & 0xFF) << 24;
Run Code Online (Sandbox Code Playgroud)