Bitmap file read/write Overview

Source: Internet
Author: User
Tags bmp image ranges readfile

Bitmap file read/write Overview
Author: Hu zhuowei, Jilin University

1. bitmap file structure

  1. Bitmap File Header
  2. Bitmap Information
    2.1 bitmap information Header
    2.2 color table
  3. Bitmap data

Ii. bitmap file read/write operations

  1. Class Declaration
  2. Bitmap reading
  3. Creating and calling a palette during bitmap reading
  4. Bitmap display
  5. Storage of Bitmap
  6. Create a new bitmap
  7. Other problems

Iii. Use of pai_dib


Download the supporting code in this article

There is a lot of information about bitmap file operations. To facilitate the work of developers, I wrote down this article and introduced the structure of Bitmap files. On this basis, I designed the generic class pai_dib for reading and writing bitmap files.

1. bitmap file structure

A bitmap file consists of three parts: File Header + bitmap information + bitmap pixel data

1. Bitmap File Header. The Bitmap header is used to identify bitmap files. The following is the definition of the bitmap file header structure:

typedef struct tagBITMAPFILEHEADER { // bmfh     WORD    bfType;     DWORD   bfSize;     WORD    bfReserved1;     WORD    bfReserved2;     DWORD   bfOffBits; } BITMAPFILEHEADER;

The value of bftype should be "BM" (0x4d42), indicating that the file is a bitmap file. The value of bfsize is the size of the bitmap file.
2. Bitmap InformationThe recorded values are used to allocate memory, set the color palette information, and read pixel values.
The following is the definition of the bitmap information structure:

 

typedef struct tagBITMAPINFO {    BITMAPINFOHEADER    bmiHeader;    RGBQUAD             bmiColors[1];} BITMAPINFO;

Visible bitmap information is composed of two parts: bitmap information header + color table

 

2.1 bitmap information header.The Bitmap header contains the number of bytes used by a single pixel and the color format. It also includes the bitmap width, height, the number of bit planes of the target device, and the compression format of the image. The following is the definition of the bitmap information header structure:

typedef struct tagBITMAPINFOHEADER{ // bmih     DWORD  biSize;     LONG   biWidth;     LONG   biHeight;     WORD   biPlanes;     WORD   biBitCount     DWORD  biCompression;     DWORD  biSizeImage;     LONG   biXPelsPerMeter;     LONG   biYPelsPerMeter;     DWORD  biClrUsed;     DWORD  biClrImportant; } BITMAPINFOHEADER; 

The following table describes the members of the struct:

Structure Member Description
Bisize The number of bytes of the bitmapinfoheader, that is, sizeof (bitmapinfoheader )*
Biwidth Image Width in pixels *
Biheight Image length in pixels *
Biplanes Number of bit planes of the target device
Bibitcount Number of digits per pixel * (1)
Bicompression Image compression format (this value is almost always 0)
Bisizeimage Size of image data in bytes (for bi_rgb compression)
Bixpelspermeter Number of pixels per meter in the horizontal direction
Biypelspermeter Number of pixels per meter in the vertical direction
Biclrused Number of colors actually used in the palette (2)
Biclrimportant Number of colors required for real Bitmap (3)

Note: * It is part of attention, because they are variables that we often refer to when performing bitmap operations.
(1) the number of bytes per pixel has the following meanings:
0, used in JPEG format
1. A monochrome image. The color palette contains two colors, that is, what we usually call a black-and-white image.
4, 16 color chart
8,256 color chart, usually grayscale
A 16, 64 k Graph with no color palette. Each two bytes in the image data represent a pixel, and five or six digits represent an RGB component.
24, 16 m true color chart, generally no color palette, each 3 bytes in the image data represents a pixel, each byte represents an RGB component
32, 4G true color, generally no color palette, each 4 bytes represents a pixel, compared to a 24-bit true color chart, a transparency is added, that is, the rgba Mode

(2) This value is usually 0, indicating all colors determined by bibitcount, except that the number of colors used for trees is smaller than the maximum number of colors in the specified color depth.

(3) This value is usually 0, indicating that all colors are required.

2.2 color table.The color table is generally set for a 16-bit image. For 16-bit and 16-bit images, the bitmap pixel data directly corresponds to the RGB (A) of the corresponding pixel) color description, thus saving the color palette. For a 16-bit image, because only the palette index value is recorded in the bitmap pixel data, the corresponding RGB (a) color needs to be obtained based on the index to the color palette. A color table is used to create a color palette.

It is a simple bitmap with or without a color palette.

Figure 1 differences between a color palette and a color palette bitmap

A color table consists of color table items. The structure of the color table items is defined as follows:

typedef struct tagRGBQUAD { // rgbq     BYTE    rgbBlue;     BYTE    rgbGreen;     BYTE    rgbRed;     BYTE    rgbReserved; } RGBQUAD;

Note that the color sequence in the rgbquad structure is BGR rather than RGB.

3. bitmap data.Finally, after the bitmap file header, bitmap information header, and bitmap color table, it is the main part of the bitmap: bitmap data. Bitmap data occupies different bytes. For example, for an 8-Bit Bitmap, each byte represents a pixel. For a 16-Bit Bitmap, each two bytes represents a pixel. For a 24-Bit Bitmap, each three bytes represents a pixel. For a 32-Bit Bitmap, each four bytes represents a pixel.

Ii. bitmap file read/write operations

After recognizing the structure of Bitmap files, it is easy to read and write specific bitmap files. The source code included in this article contains a C ++ class that facilitates bitmap read and write operations. The following provides a reference for this class and explains the key parts in the implementation code.

1. Class Declaration

Class cfg_dib: Public cobject {public: // default constructor __dib (); // constructor, based on the image width and height, record the number of bytes required for each pixel to initialize __dib (INT width, int height, int nbitcounts); Virtual ~ Pai_dib (); Public: hbitmap m_hbitmap; lpbyte m_lpdibits; // starting position of Dib; // bitmapinfoheader information lpvoid m_lpvcolortable; // hpalette m_hpalette; // palette PRIVATE: DWORD m_dwimagesize; // int m_ncolorentries of non-bitmapinfoheader or bitmapfileheader; // Number of color table items // display parameter public: cpoint m_dest; // The coordinate csize m_destsize in the upper left corner of the target rectangle; // the width and height of the rectangle cpoint m_src; // The coordinate csize m_srcsize in the lower left corner of the original rectangle; // the width and height of the original rectangle are public: void initdestroy (); // initialization Variable Void computepalettesize (INT nbitcounts); // calculate the color palette size void computeimage (); // calculate the image size // read the dib information from the BMP file bool readfile (cfile * pfile); // read the dib information from the BMP file, unlike readfile, createsection is used to create a bitmap bit bool readsection (cfile * pfile, CDC * PDC = NULL). // write DIB to a file, save it to the BMP image format bool writefile (cfile * pfile); // create a new bitmap file and allocate the memory space bool newfile (INT width, int height, int nbitcounts); // close the bitmap file bool closefile (); // display the bitmap bool display (CDC * PDC); hbitmap createbitmap (CDC * PDC ); // use DIB to create ddbhbitmap createsection (CDC * PDC = NULL); // create bitmap data, that is, pixel data. // If Dib does not have a color table, you can use the logical palette bool setlogpalette (CDC * PDC); // If Dib has a color table, you can create the system palette bool setwinpalette (); // select the logical palette of the dib object into the device environment, and then implement the uint uselogpalette (CDC * PDC) color palette. // obtain the bitmapinfoheader size, including the color table data int getheadersize () {return sizeof (bitmapinfoheader) + sizeof (rgbquad) * m_ncolorentries;} // get the Image Height int getheight () {If (m_lpbmphdr = NULL) return 0; return m_lpbmphdr-> biheight;} // get the image width int getwidth () {If (m_lpbmphdr = NULL) return 0; return m_lpbmphdr-> biwidth ;} // obtain the image size int getimagesize () {return m_dwimagesize;} Long getlinebit (); // obtain the elephant Prime Number of a row };

2. Reading bitmap.
Cfg_dib provides two methods to read bitmap data from Bitmap files: readfile and readsection. The former uses the dynamic memory allocation method to initialize the pointer to store bitmap data, the latter uses API functions to initialize the pointer to store bitmap data based on Bitmap information.

Method 1

m_lpDIBits = (LPBYTE) new char[m_dwImageSize];

Method 2

m_hBitmap = ::CreateDIBSection(pDC->GetSafeHdc(),          (LPBITMAPINFO) m_lpBMPHdr, DIB_RGB_COLORS,         (LPVOID*) &m_lpDIBits, NULL, 0);

3. Create and call the palette during bitmap reading.
This article does not provide a detailed description of the color palette. It only describes the functions that need to be called to operate the color palette during the bitmap reading process.

When the file is read, calculate the size of the palette and call the create palette function:

ComputePaletteSize(m_lpBMPHdr->biBitCount);SetWinPalette();

Set the color palette before displaying the bitmap:

if(m_hPalette != NULL) {     ::SelectPalette(pDC->GetSafeHdc(), m_hPalette, TRUE);}

4. display the bitmap.
The bitmap is displayed by calling the Windows API function. The parameters to be passed include the current bitmap information header and bitmap data:

::StretchDIBits(pDC->GetSafeHdc(), m_Dest.x, m_Dest.y,                             m_DestSize.cx, m_DestSize.cy,                             m_Src.x, m_Src.y,                             m_SrcSize.cx, m_SrcSize.cy,                             m_lpDIBits, (LPBITMAPINFO) m_lpBMPHdr,                              DIB_RGB_COLORS, SRCCOPY);

M_dest, m_destsize, m_src, and m_srcsize represent the coordinates and ranges in the upper left corner of the image displayed on the current device, and the coordinates and ranges in the lower left corner of the source image to be displayed. It should be noted that the byte array of bitmap data is stored row by row starting from the bottom line of the image, therefore, you need to pay special attention when selecting the actual range of the source bitmap!
M_dest, m_destsize, m_src, m_srcsize must be set before reality.

5. Storage of Bitmap.The storage of bitmap is implemented using writefile.
6. Create a New bitmap.Creating a New bitmap is implemented by newfile. The required parameters are the bitmap width, height, and the number of digits occupied by the bitmap pixels.
7. Other problems.There is a problem with accessing the byte array of bitmap data that needs to be noticed by developers: the number of bytes in each scanned row in the byte array must be a multiple of 4. If the number is not enough, fill it with 0.
The solution is as follows:

DWORD dwBytes = ((DWORD) m_lpBMPHdr->biWidth * m_lpBMPHdr->biBitCount) / 32;if(((DWORD) m_lpBMPHdr->biWidth * m_lpBMPHdr->biBitCount) % 32) {     dwBytes++;}dwBytes *= 4;m_dwImageSize = dwBytes * m_lpBMPHdr->biHeight;

This Code calculates the size of the byte array used to record image data as required.

Iii. Use of pai_dib

The following is the sample code for using pai_dib.

#include "fg_dib.h"CFG_DIB m_fgdib;//new filem_fgdib.NewFile(width, height, nbitnum);//open fileCFile* pf;pf = new CFile;pf->Open(sFileName, CFile::modeRead);m_fgdib.ReadFile(pf);pf->Close();delete pf;//draw BMPm_fgdib.m_Dest.x = 0;m_fgdib.m_Dest.y = 0;m_fgdib.m_DestSize.cx = m_fgdib.GetWidth();m_fgdib.m_DestSize.cy = m_fgdib.GetHeight();m_fgdib.m_Src.x = 0;m_fgdib.m_Src.y = 0;m_fgdib.m_SrcSize.cx = m_fgdib.GetWidth();m_fgdib.m_SrcSize.cy = m_fgdib.GetHeight();CDC* pDC = GetDC();m_fgdib.Display(pDC);//close BMPm_fgdib.CloseFile();

If you encounter problems when reading articles and using code, contact the author:

2001 Graduate School of Earth exploration Science and Technology, no. 6 West democratic Street, Changchun City, Jilin Province (130026)
Welcome to the author's homepage: forevergis.6to23.com

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.