Convert Win32 BITMAP into WinUI3 C++/WinRT ImageSource
See the question and my original answer on StackOverflowHere is a generic function that does that an HBITMAP
=> WinUI3 Image.Source
conversion:
#pragma comment(lib, "gdi32")
#pragma comment(lib, "oleaut32")
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams; // for InMemoryRandomAccessStream
using namespace Windows::Graphics::Imaging; // for BitmapDecoder
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::UI::Xaml::Controls; // for Image
using namespace Microsoft::UI::Xaml::Media::Imaging; // for SoftwareBitmapSource
IAsyncAction SetImageSourceFromHBITMAPAsync(HBITMAP hBitmap, Image image)
{
PICTDESC pd = {};
pd.cbSizeofstruct = sizeof(PICTDESC);
pd.picType = PICTYPE_BITMAP;
pd.bmp.hbitmap = hBitmap;
com_ptr<IPicture> picture;
if (FAILED(OleCreatePictureIndirect(&pd, IID_IPicture, FALSE, (LPVOID*)picture.put()))) // #include <olectl.h> in pch.h
return;
InMemoryRandomAccessStream memStream; // #include <winrt/Windows.Storage.Streams.h> in pch.h
com_ptr<IStream> stream;
if (FAILED(CreateStreamOverRandomAccessStream(winrt::get_unknown(memStream), IID_PPV_ARGS(&stream)))) // #include <shcore.h> in pch.h
return;
if (FAILED(picture->SaveAsFile(stream.get(), TRUE, nullptr)))
return;
auto decoder = co_await BitmapDecoder::CreateAsync(memStream); // #include <winrt/Windows.Graphics.Imaging.h> in pch.h
auto bitmap = co_await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat::Bgra8, BitmapAlphaMode::Premultiplied);
SoftwareBitmapSource bitmapSource; // #include <winrt/Microsoft.UI.Xaml.Media.Imaging.h> in pch.h
co_await bitmapSource.SetBitmapAsync(bitmap);
image.Source(bitmapSource);
}
And an example on how to use it:
namespace winrt::WinUIApp1CPP::implementation
{
MainWindow::MainWindow()
{
InitializeComponent();
}
void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
auto hBitmap = (HBITMAP)LoadImage(nullptr, L"D:\\Downloads\\dog.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE);
if (!hBitmap)
return;
auto op{ SetImageSourceFromHBITMAPAsync(hBitmap, myImage()) }; // add this XAML somewhere <Image x:Name="myImage" />
DeleteObject(hBitmap);
}
}