LoadImage
是一個Windows API函數,用于從文件或資源中加載圖像(如位圖、圖標或光標)
以下是一個簡單的示例,展示了如何在C++多線程應用程序中使用LoadImage
:
#include<iostream>
#include<thread>
#include<vector>
#include<windows.h>
void load_image(const std::wstring& file_path) {
HANDLE hFile = CreateFile(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
std::cerr << "Error opening file: "<< file_path<< std::endl;
return;
}
DWORD file_size = GetFileSize(hFile, NULL);
if (file_size == INVALID_FILE_SIZE) {
std::cerr << "Error getting file size: "<< file_path<< std::endl;
CloseHandle(hFile);
return;
}
HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
if (!hMapping) {
std::cerr << "Error creating file mapping: "<< file_path<< std::endl;
CloseHandle(hFile);
return;
}
void* data = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 1);
if (!data) {
std::cerr << "Error mapping view of file: "<< file_path<< std::endl;
CloseHandle(hMapping);
CloseHandle(hFile);
return;
}
HBITMAP hBitmap = LoadImage(NULL, file_path.c_str(), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (!hBitmap) {
std::cerr << "Error loading image: "<< file_path<< std::endl;
} else {
std::cout << "Image loaded successfully: "<< file_path<< std::endl;
}
UnmapViewOfFile(data);
CloseHandle(hMapping);
CloseHandle(hFile);
}
int main() {
std::vector<std::wstring> image_files = {L"image1.bmp", L"image2.bmp", L"image3.bmp"};
std::vector<std::thread> threads;
for (const auto& file : image_files) {
threads.emplace_back(load_image, file);
}
for (auto& thread : threads) {
thread.join();
}
return 0;
}
這個示例中,我們創建了一個名為load_image
的函數,它接受一個包含圖像文件路徑的寬字符串。然后,我們在主函數中創建了一個線程向量,并為每個圖像文件啟動一個新線程來加載圖像。最后,我們等待所有線程完成。
請注意,這個示例僅適用于Windows平臺。如果你需要在其他平臺上實現類似的功能,你可能需要使用其他庫或API。