Quest
Quest

Reputation: 2843

Load bmp file into HBITMAP

It is possible to load an image from bmp file that contain more than one image? For example i have a bmp file and i want to load an image from 12;12 to 36;36. Thanks for answer.

Upvotes: 1

Views: 2080

Answers (1)

Brandon
Brandon

Reputation: 23525

I use the following for manipulating and loading bitmaps.. It's pretty portable (except the HBitmap and draw funcs which are #ifdef'd anyway..):

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);
    }
}

If you want to convert any of the above to an hBitmap, you can do:

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;
}

Upvotes: 1

Related Questions