BMP archive. See what "BMP" is in other dictionaries. Additional information about the BMP format

In today's lesson we will look at the first file format on our path. Different file formats are designed to store different information. Each format specifies a way to organize data in a file.

We will get to know many different file formats: images, three-dimensional models, audio files, video files. Let's start with one of the simplest graphic formats - BMP.

BMP - bitmap - bitmap. The concept of "mapping" is taken from mathematics. In mathematics, a mapping is very close to the concept of a function. For simplicity, consider the word bitmap to be a picture (even though it is not).

BMP file information

Each bitmap file has a header of 14 bytes. Fields for this header:

2 bytes. BM string (on Windows).
4 bytes. File size in bytes.

2 bytes. Reserved field. Must be initialized to zero.
4 bytes. The address from which the image itself begins. Or in other words - an offset to the beginning of the image.

Let's create a 100x100 pixel image. Each pixel takes up 32 bits. The file header will look like this:

B.M.
14+40+100*100*4
0
0
14+40

Important note: these numbers are actually stored as a sequence of bytes. I hope this is clear. Here (and in the next example) I have arranged them in a column for ease of perception.

Let's deal with the second field. 14 - file header size. 40 is the size of the image title (more about it below), 100*100 is the number of pixels. And besides, since we agreed that each pixel will occupy 32 bits (4 bytes), we need to multiply the number of pixels by four.

Last field: The image itself begins immediately after the file header (14 bytes) and the image header (40 bytes).

BMP Image Information (Image Header)

There are several versions of BMP. You can determine the version by the size of the image title. We will use the Windows V3 version, which takes up 40 bytes. Other versions take 12, 64, 108, 124 bytes.

WinAPI uses the BITMAPINFOHEADER structure to store the bmp version of Windows V3.

Windows V3 header fields:

4 bytes. Header size. Always set to 40 bytes.
4 bytes. The width of the image in pixels.
4 bytes. The height of the image in pixels.
2 bytes. This field always contains one.
2 bytes. Color depth is the number of bits in a pixel.
4 bytes. Compression method.
4 bytes. Image size. The size of the image itself is indicated here - without taking into account the size of the headers.
4 bytes. Horizontal resolution in pixels per meter (the number of pixels in one meter).
4 bytes. Vertical resolution in pixels per meter (the number of pixels in one meter).
4 bytes. Number of colors in the palette.
4 bytes. The number of important colors in the palette.

Now let's see what the image title will look like in our case:

40
100
100
1
32
0
100*100*4
2795
2795
0
0

For the compression method, we chose 0 - no compression. Other values ​​are possible. Among the interesting ones: BI_JPEG (value - 4) - compression used in jpeg images and BI_PNG (value - 5) - compression used in png images.

We set the horizontal and vertical resolution to 2795. In most graphics editors, when creating an image, the resolution is set to 71 pixels per inch (ppi - pixel per inch)). So, 71ppi is 2795 pixels per meter. Resolution is used to give the image physical length (for output to a printer, for example).

After the headings there is a color palette. If it is not there, then the image immediately begins after the headings. We will not consider images with palettes for now.

BMP image data

An image is made up of pixels. The pixel format is determined by the color depth (see above). In our example we used 32 bits per pixel. 32-bit color usually consists of four channels: alpha (transparency), red, green, blue: ARGB (Alpha, Red, Green, Blue). Sometimes the alpha channel is not used, in which case the image can still occupy 32 bits, just when calculating they do not pay attention to the values ​​of one channel. In this case, the channel names are written as follows: XRGB.

Each channel occupies 8 bits (1 byte) and can take 256 values: from zero to 255 (0x00 to 0xff).

In bmp, the image is stored line by line from bottom to top, i.e. The bottom lines are written first, then the top ones. Make sure of this: load one of the images from the first exercise and save only half the lines of that image to another file.

At 32-bit color depth, channels in bmp are written as follows: BGRA. In this order: blue, green, red, alpha.

The size of the data line in the bmp image must be a multiple of four (in bytes). If this is not the case, then the string is padded with zeros. This happens if 1,2,4,8,16,24 bits per channel are used. For example, we have an image that is 3 pixels wide and we are using 16-bit color. Line width: 16*3 = 48 (6 bytes). But the length of the line must be a multiple of four, so two more bytes are added and the length of the line in this example will be eight bytes. Although the last two bytes of each line will not store useful information. It is necessary to take into account the condition that the line size is a multiple of four when working with non-32-bit images.

Now let's continue with our example and use the code to create an image. Each pixel will be initialized with a random color:

Std::ofstream os("temp.bmp", std::ios::binary); unsigned char signature = ("B", "M"); unsigned int fileSize = 14 + 40 + 100*100*4; unsigned int reserved = 0; unsigned int offset = 14 + 40; unsigned int headerSize = 40; unsigned int dimensions = ( 100, 100 ); unsigned short colorPlanes = 1; unsigned short bpp = 32; unsigned int compression = 0; unsigned int imgSize = 100*100*4; unsigned int resolution = ( 2795, 2795 ); unsigned int pltColors = 0; unsigned int impColors = 0; os.write(reinterpret_cast (signature), sizeof(signature)); os.write(reinterpret_cast (&fileSize), sizeof(fileSize)); os.write(reinterpret_cast (&reserved), sizeof(reserved)); os.write(reinterpret_cast (&offset), sizeof(offset)); os.write(reinterpret_cast (&headerSize), sizeof(headerSize)); os.write(reinterpret_cast (dimensions), sizeof(dimensions)); os.write(reinterpret_cast (&colorPlanes), sizeof(colorPlanes)); os.write(reinterpret_cast (&bpp), sizeof(bpp)); os.write(reinterpret_cast (&compression), sizeof(compression)); os.write(reinterpret_cast (&imgSize), sizeof(imgSize)); os.write(reinterpret_cast (resolution), sizeof(resolution)); os.write(reinterpret_cast (&pltColors), sizeof(pltColors)); os.write(reinterpret_cast (&impColors), sizeof(impColors)); unsigned char x,r,g,b; for (int i=0; i< dimensions; ++i) { for (int j=0; j < dimensions; ++j) { x = 0; r = rand() % 256; g = rand() % 256; b = rand() % 256; os.write(reinterpret_cast(&b),sizeof(b)); os.write(reinterpret_cast (&g),sizeof(g)); os.write(reinterpret_cast (&r),sizeof(r)); os.write(reinterpret_cast (&x),sizeof(x)); ) ) os.close();

As a result of executing this code, a temp.bmp file will be created in the folder with your project (if you ran the program through the debugger (F5)) or in the Debug folder of the solution (if you ran the executable file.exe), which can be opened in any image viewer. The image consists of colored dots.

BMP(from English Bitmap Picture) is a raster image storage format developed by Microsoft.

A huge number of programs work with the BMP format, since its support is integrated into the Windows and OS/2 operating systems. BMP files can have extensions .bmp, .dib and .rle. Additionally, data in this format is included in binary RES resource files and PE files.

Microsoft has also developed ICO and CUR formats for its needs, which have a structure similar to BMP. In addition, structures from this format are used by some WinAPI functions of the GDI subsystem.

Color depths in this format can be 1, 2, 4, 8, 16, 24, 32, 48 bits per pixel, but 2 bits per pixel is not officially supported. In this case, for color depths less than 16 bits, a palette with full-color components with a depth of 24 bits is used.

In the BMP format, images can be stored as is or using some common compression algorithms. In particular, the BMP format supports RLE compression without loss of quality, and modern operating systems and software allow the use of JPEG and PNG (these formats are built into BMP as a container).

DIB and DDB

When using the DIB format Device Independent Bitmap, device-independent raster), the programmer can access all elements of the structures that describe the image using a regular pointer. But this data is not used to directly control the screen, since it is always stored in system memory and not in dedicated video memory. The pixel format in RAM may differ from the format that must be stored in video memory to display a point of the same color. For example, the DIB format can use 24 bits to specify a pixel, and at this moment the graphics adapter can operate in HiColor mode with a color depth of 16 bits. In this case, the bright red dot will be specified in a hardware-independent format by three bytes 0x0000ff, and in video memory by the word 0xF800. When copying a picture to the screen, the system will spend additional time converting color codes from the 24-bit format to the video buffer format.

File structure overview

The BMP file consists of four parts:

  1. File header (BITMAPFILEHEADER)
  2. Image title (BITMAPINFOHEADER, may be missing). BITMAPV4HEADER (Win95, NT4.0) BITMAPV5HEADER (Win98/Me, 2000/XP)
  3. Palette (may be missing)
  4. The image itself

BITMAFILEHEADER

This structure contains information about the type, size, and representation of the data in the file. Size 14 bytes.

Typedef struct tagBITMAPFILEHEADER ( WORD bfType; // offset 0 bytes from the beginning of the file DWORD bfSize; // offset 2 bytes from the beginning of the file, length 4 bytes WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; // offset 10 bytes from the beginning of the file, length 4 bytes) BITMAPFILEHEADER, * PBITMAPFILEHEADER;

The WORD type must be 16 bits, the DWORD and LONG types must be 32 bits, the LONG type must be signed, and the byte order is assumed to be little endian.

  • bfType - file type, characters "BM" (in HEX: 0x42 0x4d).
  • bfSize - the size of the entire file in bytes.
  • bfReserved1 and bfReserved2 are reserved and must contain zeros.
  • bfOffBits - contains the offset in bytes from the beginning of the BITMAPFILEHEADER structure to the image bits themselves.

After the file header

BITMAPINFOHEADER

The simplest header option. Applications for Windows NT3.51 and earlier can only use this structure. Size 40 bytes.

Typedef struct tagBITMAPINFOHEADER( DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; ) BIT MAPINFOHEADER, * PBITMAPINFOHEADER;

BiSize The size of this structure in bytes. The BMP format has been expanded over time, and the value of this field determines the version of the format. biWidth The width of the image in pixels. For Win98/Me and Win2000/XP: If the biCompression field contains BI_JPEG or BI_PNG, this is the width of the decompressed image. biHeight The height of the image in pixels. If it contains a positive value, the image is written in bottom-to-top order (zero pixel in the lower left corner). If the value is negative, the image is written from top to bottom (zero pixel in the upper left corner of the image). The biCompression field must contain the value BI_RGB or BI_BITFIELDS. Such an image cannot be compressed. biPlanes Number of color planes and in BMP format contains one. biBitCount Number of bits per pixel. Can take the following values:

  • 0 - makes sense for Win98/Me/2000/XP. The number of bits per pixel determines the JPEG or PNG format.
  • 1 - monochrome image. The bmiColors member of the BITMAPINFO structure contains two elements. Each bit of an image represents one pixel; if the bit is zero, the pixel has the color of the first element of the bmiColors table, otherwise - the color of the second.
  • 4 - sixteen-color image. Pixels are defined by 4-bit indices, each byte of the image contains information about two pixels - the most significant 4 bits for the first, the remaining ones for the second.
  • 8 - the palette contains up to 256 colors, each byte of the image stores an index in the palette for one pixel.
  • 16 - if the biCompression field contains the value BI_RGB, the file does not contain a palette. Every two bytes of the image store the intensity of the red, green and blue components of one pixel. In this case, the most significant bit is not used; 5 bits are allocated for each component: 0RRRRRGGGGGGBBBBB.
    If the biCompression field contains the value BI_BITFIELDS, the palette stores three four-byte values ​​that define a mask for each of the three color components. Each pixel in an image is represented by a two-byte value from which color components are extracted using masks. For WinNT/2000/XP, the bit sequences of each component must follow continuously, without overlapping or intersecting with the sequences of other components. For Win95/98/Me - only the following masks are supported: 5-5-5, where the mask of the blue component is 0x001F, green 0x03E0, red 0x7C00; and 5-6-5, where the mask of the blue component is 0x001F, green 0x07E0, red 0xF800.
  • 24 - the palette is not used, each three bytes of the image represents one pixel, one byte for the intensity of the blue, green and red channels, respectively.
  • 32 - If the biCompression field contains the value BI_RGB, the image does not contain a palette. Every four bytes of the image represent one pixel, one byte each for the intensity of the blue, green and red channels, respectively. The most significant byte of each quad is not usually used, but allows storage of alpha channel data.
    If the biCompression field contains the value BI_BITFIELDS, three four-byte color masks are stored in the palette - for the red, green and blue components. Each pixel in an image is represented by four bytes. WinNT/2000: component masks must not overlap or intersect. Windows 95/98/Me: the system supports only one compression mode, completely similar to the mode without compression BI_RGB - the most significant byte of each four is used as an alpha channel, the next three are reserved for the blue, green and red channels, respectively: 0xAARRGGBB.
biCompression Compression type for compressed images:
Meaning Identifier Compression
0 BI_RGB uncompressed image
1 BI_RLE8 RLE compression for 8-bit images
2 BI_RLE4 RLE compression for 4-bit images
3 BI_BITFIELDS the image is not compressed, the palette contains three 4-byte masks for the red, green and blue color components. Used for 16 and 32 bit images
4 BI_JPEG Win98/Me/2000/XP: JPEG compression
5 BI_PNG Win98/Me/2000/XP: PNG compression
6 BI_ALPHABITFIELDS WinCE: the image is not compressed, the palette contains four 4-byte masks for the red, green, blue and transparent (alpha channel) color components. Used for 16 and 32 bit images
biSizeImage Image size in bytes. May contain zero for BI_RGB images. Win98/Me/2000/XP: If biCompression contains BI_JPEG or BI_PNG, biSizeImage specifies the size of the BI_JPEG or BI_PNG image buffer. biXPelsPerMeter Horizontal resolution in pixels per meter for the target device. An application can use this value to select from a group of image resources the most appropriate image for the current device. For DPI 96, which is accepted by Microsoft for monitors, it will be equal to 3780 (if calculated using the formula (96 / 25.4) * 1000). biYPelsPerMeter Vertical resolution in pixels per meter for the target device. biClrUsed The number of color indices used in the palette. If the value is zero, the image uses the maximum number of indexes available, according to the biBitCount value and the compression method specified in biCompression.
If contains a nonzero value and biBitCount is less than 16, biClrUsed specifies the number of colors that the device driver or application will access. If biBitCount is greater than or equal to 16, biClrUsed is the size of the palette used to optimize the performance of system palettes. If biBitCount is 16 or 32, the optimal palette follows immediately after three four-byte masks.
In a packed image, the pixel array immediately follows the BITMAPINFO structure, biClrUsed must contain zero or the actual palette size. biClrImportant The number of palette elements required to display the image. If it contains zero, all indexes are equally important.

The BITMAPINFO structure combines the BITMAPINFOHEADER and the palette, providing a complete description of the dimensions and colors of an image.

To find the palette in the BITMAPINFO structure, the application must use the information stored in biSize as follows:

PColor = ((LPSTR) pBitmapInfo + (WORD) (pBitmapInfo-> bmiHeader.biSize ) ) ;

The raster is usually stored in a vertically mirrored form. But it is also possible to store the raster in a non-vertically mirrored form. A sign that the raster in BMP is not in vertical mirror form is specified by the biHeight parameter.

BITMAPV4HEADER

An expanded version of the structure described above. Win NT 3.51 and earlier must use the BITMAPINFOHEADER structure. Win98/Me/2000/XP can use the BITMAPV5HEADER structure instead of the BITMAPV4HEADER structure.

Typedef struct ( DWORD bV4Size; LONG bV4Width; LONG bV4Height; WORD bV4Planes; WORD bV4BitCount; DWORD bV4V4Compression; DWORD bV4SizeImage; LONG bV4XPelsPerMeter; LONG bV4YPelsPerMeter; DWORD bV4ClrUsed; DWOR D bV4ClrImportant; DWORD bV4RedMask; DWORD bV4GreenMask; DWORD bV4BlueMask; DWORD bV4AlphaMask; DWORD bV4CSType ; CIEXYZTRIPLE bV4Endpoints; DWORD bV4GammaRed; DWORD bV4GammaGreen; DWORD bV4GammaBlue; ) BITMAPV4HEADER, * PBITMAPV4HEADER;

The fields from the beginning of the structure up to and including bV4ClrImportant have the same purpose as the corresponding fields of the BITMAPINFOHEADER structure.

  • bV4RedMask - color mask of the red component of each pixel, used only if bV4Compression contains the BI_BITFIELDS value.
  • bV4GreenMask - color mask of the green component of each pixel, used only if bV4Compression contains the BI_BITFIELDS value.
  • bV4BlueMask - color mask of the blue component of each pixel, used only if bV4Compression contains the BI_BITFIELDS value.
  • bV4AlphaMask - mask defining the alpha channel component.
  • bV4CSType - defines the color space of the image.
  • bV4Endpoints is a CIEXYZTRIPLE structure specifying the x, y and z coordinates of three colors that correspond to the endpoints of the color space defined for the image. This field is ignored if bV4CSType does not contain a LCS_CALIBRATED_RGB value.
  • bV4GammaRed - tone curve of the red component. Ignored if bV4CSType does not contain a LCS_CALIBRATED_RGB value. Indicated in 16×16 format.
  • bV4GammaGreen - tone curve of the green component. Ignored if bV4CSType does not contain a LCS_CALIBRATED_RGB value.
  • bV4GammaBlue - blue component tone curve. Ignored if bV4CSType does not contain a LCS_CALIBRATED_RGB value.

BITMAPV5HEADER

Win95/NT 4.0: Applications can use BITMAPV4HEADER. Win NT 3.51 and earlier must use the BITMAPINFOHEADER structure.

Typedef struct ( DWORD bV5Size; LONG bV5Width; LONG bV5Height; WORD bV5Planes; WORD bV5BitCount; DWORD bV5Compression; DWORD bV5SizeImage; LONG bV5XPelsPerMeter; LONG bV5YPelsPerMeter; DWORD bV5ClrUsed; DWORD b V5ClrImportant; DWORD bV5RedMask; DWORD bV5GreenMask; DWORD bV5BlueMask; DWORD bV5AlphaMask; DWORD bV5CSType ; CIEXYZTRIPLE bV5Endpoints; DWORD bV5GammaRed; DWORD bV5GammaGreen; DWORD bV5GammaBlue; DWORD bV5Intent; DWORD bV5ProfileData; DWORD bV5ProfileSize; DWORD bV5Reserved; ) BITMAPV5HEADER, * PBITMAPV5HEADER;

For fields from the beginning of the structure up to and including bV5GammaBlue, only differences from previous versions - BITMAPINFOHEADER and BITMAPV4HEADER will be described.

  • bV5CSType - defines the color space of the image, can take the following values:
LCS_CALIBRATED_RGB LCS_sRGB LCS_WINDOWS_COLOR_SPACE PROFILE_LINKED PROFILE_EMBEDDED
  • bV5Intent - can take the following values:
LCS_GM_ABS_COLORIMETRIC LCS_GM_BUSINESS LCS_GM_GRAPHICS LCS_GM_IMAGES
  • bV5ProfileData - offset in bytes from the beginning of the structure to the beginning of the profile data (profile file name, a string consisting exclusively of code table 1252 characters and ending with a zero byte). Ignored if bV5CSType contains a value other than PROFILE_LINKED and PROFILE_EMBEDDED.
  • bV5ProfileSize - profile data size in bytes.
  • bV5Reserved - reserved. Contains zero.

Palette

The palette can contain a sequence of four-byte fields according to the number of available colors (256 for an 8-bit image). The low three bytes of each field determine the intensity of the red, green and blue components of the color; the high byte is not used. Each pixel of the image is described in this case by one byte containing the number of the palette field in which the color of this pixel is stored.

If an image pixel is described by a 16-bit number, the palette can store three two-byte values, each of which defines a mask to extract the red, green, and blue color components from the 16-bit pixel.

A BMP file may not contain a palette if it stores an uncompressed full-color image.

Image data

A sequence of pixels recorded in one form or another. Pixels are stored row by row, from bottom to top. Each image line is padded with zeros to a length that is a multiple of four bytes.

In bmp files with a color depth of 24 bits, the color bytes of each pixel are stored in BGR (Blue, Green, Red) order.

In bmp files with a color depth of 32 bits, the color bytes of each pixel are stored in BGRA order (Blue, Green, Red, Alpha)

Image bit depth

Depending on the number of represented colors, each point is allocated from 1 to 48 bits:

  • 1 bit - monochrome image (two colors).
  • 2 bits - 4 possible colors (CGA operating modes) (2-bit mode is not officially standardized, but is used).
  • 4 bits - 16-color image (EGA operating modes).
  • 8 bits (1 byte) - 256 colors, the last of the modes to support indexed colors (see below).
  • 16 bits (2 bytes) - HiColor mode, For 5-6-5 = 65536 possible shades, for 5-5-5 = 32768 possible shades.
  • 24 bits (3 bytes) - TrueColor. Because 3 bytes do not map well to powers of two (especially when storing data in memory, where data alignment on a word boundary matters), a 32-bit image is often used instead. In TrueColor mode, each of the three channels (in RGB mode) is allocated 1 byte (256 possible values), the total number of colors is .
  • 32 bits (4 bytes) - this mode is almost similar to TrueColor, the fourth byte is usually not used, or it contains the alpha channel (transparency).
  • 48 bits (6 bytes) - a rarely used format with increased color accuracy (16 bits per channel), supported by a relatively small number of programs and equipment.

Indexed colors

When the number of bits is 1 (2 colors), 2 (4 colors), 4 (16 colors) or 8 (256 colors) per pixel, a special indexed color mode can be used. In this case, the number corresponding to each pixel does not indicate the color, but the number of the color in the palette. By using a palette, it is possible to adapt the image to the colors present in the image. In this case, the image is limited not by specified colors, but by the maximum number of colors used simultaneously.

Example program

The following program opens a 24-bit BMP file in an XWindow, the color depth should be 32 bits, it does not work at lower color renderings, as it complicates the example:

/* Compiled with the line: cc -o xtest xtest.c -I/usr/X11R6/include -L/usr/X11R6/lib -lX11 -lm */#include #include #include #include #include #include #include #include #include #include #include #include "bitmap.h" /* Here are the BMP header definitions as described earlier in this article */ static XImage * CreateImageFromBuffer(Display*, unsigned char *, int, int) ; main(int argc, char * argv ) ( Display * dis; Window win; /* Our window */ XEvent event; /* Events */ GC gc; /* Graphics context */ XImage * image; int n, width, height, fd, size; unsigned char * data; BITMAPFILEHEADER bmp; BITMAPINFOHEADER inf; char * buf; if (argc< 2 ) { perror ("use: xtest file.bmp\n") ; exit(1); ) if ((fd = open(argv[ 1 ] , O_RDONLY) ) == - 1 ) ( printf ("Error open bitmap \n") ; exit(1); ) read(fd, & bmp, sizeof (BITMAPFILEHEADER) ) ; read(fd, & inf, sizeof (BITMAPINFOHEADER) ) ; width = inf.biWidth ; height = inf.biHeight ; if ((dis = XOpenDisplay(getenv ("DISPLAY" ) ) ) == NULL) ( printf ( "Can"t connect X server: %s\n ", strerror (errno) ) ; exit(1); ) win = XCreateSimpleWindow(dis, RootWindow(dis, DefaultScreen(dis) ) , 0 , 0 , width, height, 5 , BlackPixel(dis, DefaultScreen(dis) ) , WhitePixel(dis, DefaultScreen(dis) ) ) ; XSetStandardProperties(dis, win, argv[ 1 ], argv[ 0 ], None, argv, argc, NULL); gc = DefaultGC(dis, DefaultScreen(dis) ) ; /* Sometimes this space in the structure is not filled */ if (inf.biSizeImage == 0 ) ( /* Calculate the size */ size = width * 3 + width % 4 ; size = size * height; ) else ( size = inf.biSizeImage ; ) buf = malloc (size) ; if (buf == NULL) ( perror ("malloc" ) ; exit (1 ) ; ) printf ( "size = %d bytes allocated\n ", size) ; /* Let's move to the beginning of the image itself */ lseek(fd, bmp.bfOffBits , SEEK_SET) ; /* Read into the buffer */ n = read(fd, buf, size) ; printf( "size = %d bytes read\n ", n) ; image = CreateImageFromBuffer(dis, buf, width, height) ; /* Delete the buffer - we no longer need it */ free(buf); XMapWindow(dis, win) ; XSelectInput(dis, win, ExposureMask | KeyPressMask) ; while (1 ) ( XNextEvent(dis, & event) ; if (event.xany .window == win) ( switch (event.type ) ( case Expose: XPutImage(dis, win, gc, image, 0 , 0 , 0 , 0 , image-> width, image-> height) ; break ; case KeyPress: if (XLookupKeysym(& event.xkey , 0 ) == XK_q) ( XDestroyImage(image) ; XCloseDisplay(dis) ; close(fd) ; exit (EXIT_SUCCESS) ; ) break ; default : break ; ) ) ) ) /* Creates a Ximage from a BMP file, since the BMP image is stored upside down * and mirrored - this is corrected in a loop */ XImage * CreateImageFromBuffer(Display * dis, unsigned char * buf, int width, int height) ( int depth, screen; XImage * img = NULL; int i, j; int numBmpBytes; size_t numImgBytes; int32_t * imgBuf; int ind = 0 ; int line; int temp; int ih, iw; /* Row and column numbers to reflect */ int new_ind; /* New index */ screen = DefaultScreen(dis) ; depth = DefaultDepth(dis, screen) ; temp = width * 3 ; line = temp + width % 4 ; /* String length taking into account alignment */ numImgBytes = (4 * (width * height) ) ; imgBuf = malloc(numImgBytes); /* Size allocated to BMP in the file, taking into account alignment */ numBmpBytes = line * height; for (i = 0 ; i< numBmpBytes; i++ ) { unsigned int r, g, b; /* Skip padding */ if (i >= temp && (i % line) >= temp) continue ; b = buf[ i] ; i++; g = buf[ i] ; i++; r = buf[ i] ; /* Calculate a new index for vertical reflection */ iw = ind % width; ih = ind / width; new_ind = iw + (height - ih - 1 ) * width; imgBuf[ new_ind] = (r | g<< 8 | b << 16 ) << 8 ; ind++; } img = XCreateImage(dis, CopyFromParent, depth, ZPixmap, 0 , (char * ) imgBuf, width, height, 32 , 0 ) ; XInitImage(img) ; /* Bit and byte order on PC should be like this */ img->byte_order = MSBFirst; img->bitmap_bit_order = MSBFirst; return img; )

The bmp file format is a raster image and is quite popular. It is well “understood” by any Windows operating system.

Opening a file with the bmp extension on your computer should happen automatically - just double-click on it with the left mouse button.

If this does not happen for you, then most likely the file association is broken, then the system needs to manually specify what to open it with.

To do this, right-click on your bmp file, move the cursor to the “open with” line and select any program (if installed) of your choice, for example Paint.

Which program to open the bmp extension

The easiest way to open the bmp format is in the Windows photo album program. There is no need to download it - it comes with the operating system, that is, everyone should have it.

The second program is “Paint”. There is also no need to download it - it is built into Windows by default, in addition, you can not only edit the bmp extension, but after opening it, save it in another format, for example jpg - for viewing on your phone.

The third program is “PhotoScape”. You will have to download it. It is free, in Russian and with its help, in addition to viewing, you can process bmp images.

The fourth Paint.NET application. It is also free, has a Russian interface, is convenient and very easy to use, with many tools for adjusting and editing images and photos - it’s like a substitute for the standard “Paint”

Fifth program "GIMP". It is compared to photoshop. This is a free graphic editor for professional use that has all the necessary functions and is characterized by simplicity.

The programs provided above that open files in this format are not all. There are dozens of them, but these are quite enough for the average computer user. Good luck.

BMP is a popular image format without data compression. Let's look at what programs you can use to view pictures with this extension.

Probably, many have already guessed that since the BMP format is used to display pictures, you can view the contents of these files using image viewers and graphic editors. In addition, some other applications, such as browsers and universal viewers, can handle this task. Next, we will look at the algorithm for opening BMP files using specific software.

Method 1: FastStone Image Viewer

Let's start with the popular image viewer FastStone Viewer.


Method 2: IrfanView

Now let's look at the process of opening a BMP in another popular image viewer IrfanView.


Method 3: XnView

The next image viewer in which we will look at opening a BMP file is XnView.


Method 4: Adobe Photoshop

Now let's move on to describing the algorithm of actions for solving the described problem in graphic editors, starting with the popular application Photoshop.


The main disadvantage of this method is that the Photoshop application is paid.

Method 5: Gimp

Another graphics editor that can display BMP is Gimp.


Compared to the previous method, this one benefits from the fact that the Gimp application does not require payment for its use.

Method 6: OpenOffice

The Draw graphic editor, which is included in the free OpenOffice package, also successfully copes with this task.


Method 7: Google Chrome

Not only graphic editors and image viewers can open BMP, but also a number of browsers, for example Google Chrome.


Method 8: Universal Viewer

Another group of programs that can work with BMP are universal viewers, which includes the Universal Viewer application.


Method 9: Paint

The methods for opening BMP using third-party installed programs were listed above, but Windows has its own graphics editor - Paint.


Method 10: Windows Photo Viewer

Windows also has a built-in image-only viewer that can be used to launch BMP. Let's look at how to do this using Windows 7 as an example.


As you can see, there is a fairly large list of programs that can open BMP images. And these are not all of them, but only the most popular. The choice of a specific application depends on the user’s personal preferences, as well as on the goals set. If you just need to look at a drawing or photo, then it is better to use picture viewers, and for editing, use image editors. In addition, even browsers can be used as an alternative for viewing. If the user does not want to install additional software on the computer to work with BMP, he can use the built-in Windows software to view and edit images.

A small program was considered that moved the sprite around the screen, but, unfortunately, it did not look as we would like. In this article we will try to “tidy up” the sprite.

We obtained the sprite image from a Bmp file; from the same files we can take the image of the background, mouse cursor and interface elements. However, what we see on the screen is not exactly what we expected: the image turned out to be upside down and, moreover, with different colors than required. So, let’s learn how to read Bmp files correctly and turn the picture “from head to toe.”

By decision of the developers, the Bmp file format is not tied to a specific hardware platform. This file consists of four parts: a header, an information header, a color table (palette), and image data. If the file stores an image with a color depth of 24 bits (16 million colors), then the color table may be missing, but in our 256-color case it is there. The structure of each part of a file storing a 256-color image is given in , and the corresponding record types are given in .

The file header starts with signatures"BM" followed by the length of the file, expressed in bytes. The next 4 bytes are reserved for further format extensions, and this header ends displacement from the beginning of the file to the image data recorded in it. With 256 colors, this offset is 1078 - this is exactly how much we had to skip in our previous program to get to the data.

The information header starts with its own length (this can vary, but for a 256-color file it is 40 bytes) and contains the image dimensions, resolution, color presentation characteristics and other parameters.

Image width and height are specified at raster points and probably do not require explanation.

Number of planes could be used in files with low color depth. When the number of colors is 256 or more, it is always equal to 1, so this field can now be considered obsolete, but for compatibility it is retained.

Color depth is considered the most important characteristic of the way color is represented in a file and is measured in bits per dot. In this case it is equal to 8.

Compression. It is usually not used in Bmp files, but a field in the header is provided for it. Typically it is 0, which means the image is not compressed. In the future we will use only such files.

Image Size- the number of bytes of memory required to store this image, not counting the palette data.

Horizontal and vertical resolutions measured in raster points per meter. They are especially important for maintaining the scale of scanned images. Images created using graphic editors usually have zeros in these fields.

Number of colors allows you to reduce the size of the palette table if the image actually contains fewer colors than the selected color depth allows. However, in practice such files are almost never found. If the number of colors is the maximum allowed by the color depth, for example 256 colors at 8 bits, the field is set to zero.

Number of primary colors- comes from the beginning of the palette, and it is advisable to display it without distortion. This field is important when the maximum number of display colors was less than in the Bmp file palette. When developing the format, it was obviously assumed that the most frequently occurring colors would be located at the beginning of the table. Now this requirement is practically not followed, i.e. colors are not ordered by the frequency with which they occur in the file. This is very important, since the palettes of two different files, even composed of the same colors, would contain them (the colors) in a different order, which could significantly complicate the simultaneous display of such images on the screen.

The information header is followed by a color table, which is an array of 256 (in number of colors) 4-byte fields. Each field corresponds to a color in the palette, and three of the four bytes correspond to the blue, green, and red components of that color. The last, most significant byte of each field is reserved and equal to 0.

After the color table there is image data, which is written along the raster lines from bottom to top, and inside the line - from left to right. Since on some platforms it is impossible to read a data unit that is less than 4 bytes, the length of each line is aligned to a boundary of 4 bytes, i.e., if the line length is not a multiple of four, it is padded with zeros. This circumstance must be taken into account when reading the file, although it may be better to ensure in advance that the horizontal dimensions of all images are a multiple of 4.

As we have already said, the file format was designed to be universal for various platforms, so it is not surprising that the palette colors are stored in it differently than is customary for VGA. During the reading procedure, the necessary recoding is performed. (We will talk about what the VGA palette is and how to work with it in the following articles.)

The module for reading 256-color Bmp files has only two procedures. As can be seen from the listing, the image dimensions must be passed to the ReadBMP file reading procedure. This is convenient if the image does not need to be read completely. When the sizes are known in advance, this does not cause problems, but it would be good if, using our module, it was possible to read any images, including those whose size is unknown in advance. For this purpose, the ReadBMPheader procedure is provided, which reads only the file header. By calling it, you can check whether the image is recorded in the selected 256-color format, find out its dimensions, and only then allocate memory for it and place it in the allocated buffer.

Now let's connect a new module to our program. To do this, we will write its name in the uses directive, and also provide an array for storing data about the palette, which can be described like this:

P: arrayof byte;

The CreateSprite procedure, which calls the operation to read a file from a new module, has been simplified (see).

Bmp file structure

Name Length Bias Description
File header (BitMapFileHeader)
Type2 0 Signature "BM"
Size4 2 file size
Reserved 12 6 Reserved
Reserved 22 8 Reserved
OffsetBits4 10 Image offset from the beginning of the file
Information header (BitMapInfoHeader)
Size4 14 Header length
Width4 18 Image width, points
Height4 22 Image height, points
Planes2 26 Number of planes
BitCount2 28 Color depth, bits per dot
Compression4 30 Compression type (0 - uncompressed image)
SizeImage4 34 Image size, bytes
XpelsPerMeter4 38 Horizontal resolution, dots per meter
YpelsPerMeter4 42 Vertical resolution, dots per meter
ColorsUsed4 46 Number of colors used (0 is the maximum possible for a given color depth)
ColorsImportant4 50 Number of primary colors
Color table (palette)
ColorTable1024 54 256 elements of 4 bytes
Image Data (BitMap Array)
ImageSize1078 Image recorded in rows from left to right and bottom to top

Listing 1

unit bmpread; (procedures for working with Bmp) interface type artype = arrayof byte; arptr = ^artype; bmFileHeader = record (file header) Typf: word; (signature ) Size: longint; (file length in bytes) Res1: word; (reserved) Res2: word; (reserved) OfBm: longint; (image offset in bytes (1078)) end; bmInfoHeader = record (information header) Size: longint; (header length in bytes (40)) Widt: longint; (image width (in pixels)) Heig: longint; (image height (in pixels)) Plan: word; (number of planes (1)) BitC: word; (color depth (bits per dot) (8)) Comp: longint; (compression type (0 - no)) SizI: longint; (image size in bytes) XppM: longint; (horizontal resolution) ((dots per meter - usually 0)) YppM: longint; (vertical resolution) ((dots per meter - usually 0)) NCoL: longint; (number of colors) ((if the maximum allowed is 0)) NCoI: longint; (number of primary colors) end; bmHeader = record (full file header) f: bmFileHeader; (file header) i: bmInfoHeader; (information header) p: arrayof byte; (palette table) end; bmhptr = ^bmHeader; (reading an image from a Bmp file) procedure ReadBMP(image:arptr; (array with image) xim,yim:word; (dimensions) pal:arptr; (palette) filename:string); (file name) (reading Bmp file header) procedure ReadBMPheader(header:bmhptr;filename:string); implementation ($R-) (reading an image from a Bmp file) procedure ReadBMP(image:arptr; xim,yim:word; pal:arptr; filename:string); var h: bmHeader; i:integer; bmpfile: file; s: longint; begin assign(bmpfile,filename); reset(bmpfile,1); blockread(bmpfile,h,sizeof(h)); (read header) for i:= 0 to yim-1 do begin (read line by line) blockread(bmpfile,image^[(yim-i-1)*xim],xim); if (xim mod 4)<>0 then blockread(bmpfile,s,4 - (xim mod 4)); end; close(bmpfile); for i ^= 0 to 255 do begin (palette transformation) pal^ := h.p shr 2; (blue) pal^ := h.p shr 2; (green) pal^ := h.p shr 2; (red) end; end; (reading the header of a Bmp file) procedure ReadBMPheader(header:bmhptr;filename:string); var bmpfile:file; begin assign(bmpfile,filename); reset(bmpfile,1); blockread(bmpfile,header^,sizeof(header^)); close(bmpfile); end; end.

Listing 2

( sprite) procedure CreateSprite(s:string; x,y,dx,dy:integer); var f: file; (file with sprite image) begin getmem(Sprt.Img,sizeof(SpriteArrayType)); (allocate memory for the sprite) getmem(Sprt.Back,sizeof(SpriteArrayType)); (allocate memory for the buffer) Readbmp(@(Sprt.Img^),Xsize,Ysize,@p,s); Sprt.x:= x; Sprt.y:=y; (set the initial values) Sprt.dx:= dx; (coordinates and increments) Sprt.dy:= dy; end; Emulators