Search code examples
javaimageheaderbitmapbmp

Java BMP Header files


I try to make a BMP file from BufferedImage. Here is function with that I try to write the header and pixels in bmp file.

I have a mistake but I can't find that. I need your help.

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();
    }
}

I tried to write only header, and header size = 54 bytes.

I don't know if I calculate correct the bfSize and biSizeImage.


Solution

  • To resolve my problem I need to use LITTLE_ENDIAN byte order. For this I use:

        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();