Search code examples
javaandroidimagebmp

Creating 24bit BMP fails (only with a particular resolution)


I'm creating a 24bit bmp which in general works fine (I've been using this functionality for some time). Now I've tried to write a bmp with 970 x 970 pixels and I'm ending up in corrupt files (I've exported bigger images before, I'm having problems with this particular resolution).

This is how I build the header:

private static byte[] createHeader(int width, int height) {
    int size = width * height * 3 + 54;

    byte[] ret = new byte[54];

    set(ret, 0, (byte) 'B', (byte) 'M');
    set(ret, 2, intToDWord(size));
    set(ret, 6, intToDWord(0));
    set(ret, 10, intToDWord(54));
    set(ret, 14, intToDWord(40));
    set(ret, 18, intToDWord(width));
    set(ret, 22, intToDWord(height));
    set(ret, 26, intToWord(1));
    set(ret, 28, intToWord(24));
    set(ret, 30, intToDWord(0));
    set(ret, 34, intToDWord(width * height * 3));
    set(ret, 38, intToDWord(0));
    set(ret, 42, intToDWord(0));
    set(ret, 46, intToDWord(0));
    set(ret, 50, intToDWord(0));

    return ret;
}

Here is the resulting image (this test image should be completely red): test_corrupt.bmp (2.6mb)

I've analyzed the header, checked the size, I can't find the reason why this image is not a valid BMP.

Does anyone have a clue? I'm not making any progress.


Solution

  • It may be because of BMP files expects row lengths to be a multiple of 4 bytes. This changes the size you specified in header offset 34 and therefore the size in offset 2. Please refer to the following for details:

    http://en.wikipedia.org/wiki/BMP_file_format

    Related Part:

    For file storage purposes, only the size of each row must be a multiple of 4 bytes while the file offset can be arbitrary

    You can compare file by creating a 970x970 Red BMP file using MS Paint.