将bmp文件加载到HBITMAP中

时间:2013-12-31 17:03:18

标签: c++ bitmap

可以从包含多个图像的bmp文件加载图像吗? 例如,我有一个bmp文件,我想加载12; 12到36; 36的图像。 谢谢你的回答。

1 个答案:

答案 0 :(得分:1)

我使用以下内容来操作和加载位图..它非常便携(除了HBitmap和绘制函数,无论如何都是#ifdef)。):

<强> Images.hpp:

#ifndef IMAGES_HPP_INCLUDED
#define IMAGES_HPP_INCLUDED

#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <stdexcept>
#include <windows.h>

namespace CG
{
    typedef union RGBA
    {
        std::uint32_t Colour;
        struct
        {
            std::uint8_t R, G, B, A;
        };
    } *PRGB;

    class Image
    {
        private:
            RGBA* Pixels;
            std::uint32_t width, height;
            std::uint16_t BitsPerPixel;

        protected:

        public:
            ~Image();

            Image(HWND Window, int X, int Y, int Width, int Height);
    };
}

#endif // IMAGES_HPP_INCLUDED

<强> Images.cpp:

#include "Images.hpp"

namespace CG
{
    Image::~Image()
    {
        delete[] this->Pixels;
    }

    Image::Image(HWND Window, int X, int Y, int Width, int Height)
    {
        HDC DC = GetDC(Window);
        BITMAP Bmp = {0};
        HBITMAP hBmp = reinterpret_cast<HBITMAP>(GetCurrentObject(DC, OBJ_BITMAP));

        if (GetObject(hBmp, sizeof(BITMAP), &Bmp) == 0)
            throw std::runtime_error("BITMAP DC NOT FOUND.");

        RECT area = {X, Y, X + Width, Y + Height};
        GetClientRect(Window, &area);

        HDC MemDC = GetDC(nullptr);
        HDC SDC = CreateCompatibleDC(MemDC);
        HBITMAP hSBmp = CreateCompatibleBitmap(MemDC, width, height);
        DeleteObject(SelectObject(SDC, hSBmp));

        BitBlt(SDC, 0, 0, width, height, DC, X, Y, SRCCOPY);
        this->Pixels = new RGBA[width * height];

        BITMAPINFO Info = {sizeof(BITMAPINFOHEADER), width, height, 1, BitsPerPixel, BI_RGB, Data.size(), 0, 0, 0, 0};
        GetDIBits(SDC, hSBmp, 0, height, this->Pixels, &Info, DIB_RGB_COLORS);

        DeleteDC(SDC);
        DeleteObject(hSBmp);
        ReleaseDC(nullptr, MemDC);
        ReleaseDC(Window, DC);
    }
}

如果您想将上述任何内容转换为hBitmap,您可以执行以下操作:

HBITMAP Image::ToHBitmap()
{
    void* Memory = this->Pixels;        
    std::size_t size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
    BITMAPINFO Info = {sizeof(BITMAPINFOHEADER), width, height, 1, BitsPerPixel, BI_RGB, size, 0, 0, 0, 0};
    HBITMAP hBmp = CreateDIBSection(nullptr, &Info, DIB_RGB_COLORS, &Memory, nullptr, 0);
    return hBmp;
}