Java BMP头文件

时间:2013-02-14 22:19:45

标签: java image header bitmap bmp

我尝试从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。

2 个答案:

答案 0 :(得分:2)

尝试使用ImageIO

File outImage = new File(name);
ImageIO.write(img, "bmp", outImage);

答案 1 :(得分:1)

要解决我的问题,我需要使用LITTLE_ENDIAN字节顺序。为此,我使用:

    ByteBuffer buffer = ByteBuffer.allocate(54);
    buffer.putInt(bfSize);
    buffer.putShort(bfReserved1);
    buffer.putShort(bfReserved2);
    buffer.putInt(bfOfBytes);
    buffer.putInt(biSize);
    buffer.putInt(biWidth);
    buffer.putInt(biHeight);
    buffer.putShort(biPlanes);
    buffer.putShort(biBitCount);
    buffer.putInt(biSizeImage);
    buffer.putInt(biXPelsPerMeter);
    buffer.putInt(biYPelsPerMeter);

    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.flip();