将内存位图转换为jpg文件,c++

问题描述 投票:0回答:1

我想将位图转换为 jpg 文件并使用 std::fstream 保存它,但我不能。

我用谷歌搜索但没有找到任何解决方案

这是我的代码,如何将 hBitmap 转换为 jpg 文件?

#include <Windows.h>
#include <Shldisp.h>

int main()
{

    HDC hScreenDC = GetDC(nullptr); // CreateDC("DISPLAY",nullptr,nullptr,nullptr);
    HWND hwnd = WindowFromDC(hScreenDC); //I added this
    HDC hMemoryDC = CreateCompatibleDC(hScreenDC);
    int width = GetDeviceCaps(hScreenDC, HORZRES);
    int height = GetDeviceCaps(hScreenDC, VERTRES);
    HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, width, height);

    HBITMAP hOldBitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hBitmap));
    BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY);
    hBitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hOldBitmap));


    DeleteDC(hMemoryDC);
    ReleaseDC(hwnd, hScreenDC);
}
c++ winapi bitmap screenshot
1个回答
0
投票

@boost 你不妨使用

std::fstream
。确保下载 FreeImage 库并将其包含在您的项目中。

这是如何使用 FreeImage 将位图保存为 JPEG 文件的示例:

#include <Windows.h>
#include <FreeImage.h>
#include <iostream>
#include <fstream>

int main() {
    HDC hScreenDC = GetDC(nullptr);
    int width = GetDeviceCaps(hScreenDC, HORZRES);
    int height = GetDeviceCaps(hScreenDC, VERTRES);

    HBITMAP hBitmap = CreateCompatibleBitmap(hScreenDC, width, height);
    HDC hMemoryDC = CreateCompatibleDC(hScreenDC);

    HBITMAP hOldBitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hBitmap));
    BitBlt(hMemoryDC, 0, 0, width, height, hScreenDC, 0, 0, SRCCOPY);

    hBitmap = static_cast<HBITMAP>(SelectObject(hMemoryDC, hOldBitmap));
    DeleteDC(hMemoryDC);
    ReleaseDC(nullptr, hScreenDC);

    // Initialize FreeImage
    FreeImage_Initialise();

    // Create a FreeImage bitmap from the HBITMAP
    FIBITMAP* fiBitmap = FreeImage_ConvertFromHBitmap(hBitmap, nullptr);
    DeleteObject(hBitmap);

    if (fiBitmap) {
        // Save the FreeImage bitmap as a JPEG file
        if (FreeImage_Save(FIF_JPEG, fiBitmap, "output.jpg", 0)) {
            std::cout << "Image saved successfully." << std::endl;
        } else {
            std::cerr << "Failed to save the image." << std::endl;
        }

        FreeImage_Unload(fiBitmap);
    } else {
        std::cerr << "Failed to convert HBITMAP to FreeImage bitmap." << std::endl;
    }

    // Deinitialize FreeImage
    FreeImage_DeInitialise();

    return 0;
}

确保将您的项目与 FreeImage 库链接。您可以从官方网站下载:.

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.