Published by orzz.org(). (http://orzz.org/%e5%8a%a0%e8%bd%bdbmp%e6%96%87%e4%bb%b6/)
这里给出的加载方法并没有考虑图片文件可能出现的所有情况,只是一个简单的解析过程.
加载后的HBITMAP指向一个32位DIB(这里这样做是为了统一png/jpg/bmp在加载之后的像素处理与显示).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
FILE* file = _tfopen(s_name, _T("rb")); if (file) { // 填充图像缓冲区 fseek(file, 0, SEEK_END); DWORD size = ftell(file); fseek(file, 0, SEEK_SET); BYTE* data = (BYTE*)ZeroMemory(malloc(size), size); fread(data, 1, size, file); // 将BYTE*转换为HBITMAP BITMAPFILEHEADER* pbmh = (BITMAPFILEHEADER*)data; if (pbmh->bfType == 0x4D42) { BYTE* pbits = data + sizeof(BITMAPFILEHEADER); BITMAPINFO* pbmi = (BITMAPINFO*)pbits; BITMAPINFO bmi = {0}; bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biSizeImage = pbmi->bmiHeader.biSizeImage; bmi.bmiHeader.biWidth = pbmi->bmiHeader.biWidth; bmi.bmiHeader.biHeight = pbmi->bmiHeader.biHeight; COLORREF* bmbf = NULL; hBitmap = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void**)&bmbf, NULL, 0); if (bmbf) { pbits += sizeof(BITMAPINFO); for(int y = 0; y < bmi.bmiHeader.biHeight; ++y) { int pos = bmi.bmiHeader.biWidth * y; int inx = bmi.bmiHeader.biWidth * 3 * y; for(int x = 0; x < bmi.bmiHeader.biWidth; ++x, inx += 3, ++pos) bmbf[pos] = RGB(pbits[inx + 2], pbits[inx], pbits[inx + 1]); } } } // 释放资源 free(data); fclose(file); } |
之后的HBITMAP需要手动调用DeleteObject释放.
Published by orzz.org(). (http://orzz.org/%e5%8a%a0%e8%bd%bdbmp%e6%96%87%e4%bb%b6/)