我尝试从 BufferedImage 制作 BMP 文件。这是我尝试在 bmp 文件中写入标题和像素的功能。
我有一个错误,但我找不到。我需要你的帮助。
static void writeToBMP(BufferedImage img, String name)
{
//File header
int bfType = 0x424d;
int bfSize = (img.getHeight()*img.getWidth()*3)+54; // File size
short bfReserved1 = 0; // Reserved
short bfReserved2 = 0;
int bfOfBytes = 54; // Header size
//Header info
int biSize = 40; // Header 2 size
int biWidth = img.getWidth(); // Width in pixels
int biHeight = img.getHeight(); // Height in pixels
short biPlanes = 1; // Nr of planes
short biBitCount = 24; // Nr bites per pixel
int biCompression = 0;
int biSizeImage = (img.getHeight()*img.getWidth()*3); // Image size
int biXPelsPerMeter = 0;
int biYPelsPerMeter = 0;
int biClrUsed = 0;
int biClrImportant = 0;
File file = new File(name);
try {
OutputStream stream = new FileOutputStream(file);
fOut = new DataOutputStream(stream);
fOut.writeShort(bfType);
fOut.writeInt(bfSize);
fOut.writeShort(bfReserved1);
fOut.writeShort(bfReserved2);
fOut.writeInt(bfOfBytes);
//Write Header Info
fOut.writeInt(biSize);
fOut.writeInt(biWidth);
fOut.writeInt(biHeight);
fOut.writeShort(biPlanes);
fOut.writeShort(biBitCount);
fOut.writeInt(biCompression);
fOut.writeInt(biSizeImage);
fOut.writeInt(biXPelsPerMeter);
fOut.writeInt(biYPelsPerMeter);
fOut.writeInt(biClrUsed);
fOut.writeInt(biClrImportant);
for(int x=0; x<img.getWidth(); x++)
{
for(int y=0; y<img.getHeight(); y++)
{
Color c = new Color(img.getRGB(x,y));
fOut.writeByte(c.getRed());
fOut.writeByte(c.getBlue());
fOut.writeByte(c.getGreen());
}
}
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我试图只写标题,标题大小 = 54 字节。
我不知道我计算的 bfSize 和 biSizeImage 是否正确。