各位老大,帮我看看代码
//
The DataInputStream allows you to read in 16 and 32 bit numbers
DataInputStream in
=
new
DataInputStream(instream);
DataOutputStream out
=
new
DataOutputStream(outstream);
//
Verify that the header starts with 'BM'

if
(in.read()
!=
'
B
'
)
{
throw
new
IOException(
"
Not a .BMP file
"
);
}
out.write(
'
B
'
);

if
(in.read()
!=
'
M
'
)
{
throw
new
IOException(
"
Not a .BMP file
"
);
}
out.write(
'
M
'
);
//
Get the total file size
int
fileSize
=
intelInt(in.readInt());
out.writeInt(intelInt(fileSize));
//
Skip the 2 16-bit reserved words
out.writeShort(in.readUnsignedShort());
out.writeShort(in.readUnsignedShort());
int
bitmapOffset
=
intelInt(in.readInt());
out.writeInt(intelInt(bitmapOffset));
int
bitmapInfoSize
=
intelInt(in.readInt());
out.writeInt(intelInt(bitmapInfoSize));
int
width
=
intelInt(in.readInt());
out.writeInt(intelInt(width));
int
height
=
intelInt(in.readInt());
out.writeInt(intelInt(height));
//
Skip the 16-bit bitplane size
out.writeShort(in.readUnsignedShort());
int
bitCount
=
intelShort(in.readUnsignedShort());
out.writeShort(intelShort(bitCount));
int
compressionType
=
intelInt(in.readInt());
out.writeInt(intelInt(compressionType));
int
imageSize
=
intelInt(in.readInt());
out.writeInt(intelInt(imageSize));
//
Skip pixels per meter
out.writeInt(in.readInt());
out.writeInt(in.readInt());
int
colorsUsed
=
intelInt(in.readInt());
out.writeInt(intelInt(colorsUsed));
int
colorsImportant
=
intelInt(in.readInt());
out.writeInt(intelInt(colorsImportant));
System.out.println(
"
[colorused]=
"
+
colorsUsed);
//
Read the pixels from the stream based on the compression type

if
(compressionType
==
BI_RGB)
{
if
(bitCount
==
24
)
{
readRGB24(width, height, in, out);
}
}
}
protected
static
void
readRGB24(
int
width,
int
height,
DataInputStream in, OutputStream out)
throws
IOException
{
//
Start storing at the bottom of the array

for
(
int
h
=
height
-
1
; h
>=
0
; h
--
)
{
for
(
int
w
=
0
; w
<
width; w
++
)
{
//
Read in the red, green, and blue components
int
red
=
in.read();
int
green
=
in.read();
int
blue
=
in.read();
out.write(red);
out.write(green);
out.write(blue);
}
}
}
本文介绍了一段用于读取并转换BMP文件的Java代码实现。代码使用DataInputStream和DataOutputStream处理文件输入输出,确保文件头正确,并逐像素读取24位彩色BMP图片,最终实现了BMP文件的有效解析。
262

被折叠的 条评论
为什么被折叠?



