简体   繁体   English

将bmp文件加载到HBITMAP中

[英]Load bmp file into HBITMAP

It is possible to load an image from bmp file that contain more than one image? 是否可以从包含多个图像的bmp文件中加载图像? For example i have a bmp file and i want to load an image from 12;12 to 36;36. 例如,我有一个bmp文件,我想将图像从12; 12加载到36; 36。 Thanks for answer. 感谢您的回答。

I use the following for manipulating and loading bitmaps.. It's pretty portable (except the HBitmap and draw funcs which are #ifdef 'd anyway..): 我使用以下代码来操作和加载位图。.它非常可移植(除了HBitmap和绘制函数,它们始终是#ifdef 。):

Images.hpp: 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: 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);
    }
}

If you want to convert any of the above to an hBitmap, you can do: 如果要将以上任何内容转换为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM