Microsoft Dev Blogs

How can I convert a Windows Runtime Software­Bitmap to a WIC bitmap?

thumbnail

Converting a Windows Runtime Software­Bitmap to a WIC bitmap

To convert a Windows Runtime Software­Bitmap to a WIC (Windows Imaging Component) bitmap, you can use the IWICBitmapSource interface to access and convert the underlying pixel data.

Here is an example of how you can do this:

  1. If the Software­Bitmap is in a video format (i.e., BitmapPixelFormat.Videos), you need to first convert it to a WIC format.
if (bitmap.BitmapPixelFormat == BitmapPixelFormat.Videos)
{
    var stream = new InMemoryRandomAccessStream();
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
    encoder.SetSoftwareBitmap(bitmap);
    await encoder.FlushAsync();
    
    var decoder = await BitmapDecoder.CreateAsync(BitmapDecoder.BmpDecoderId, stream);
    var convertedSoftwareBitmap = await decoder.GetSoftwareBitmapAsync();
    bitmap = SoftwareBitmap.Convert(convertedSoftwareBitmap, BitmapPixelFormat.Bgra8);
}
  1. Once you have a Software­Bitmap that's not in a video format, you can access its pixel data as a WIC bitmap using the IWICBitmapSource interface.
IWICImagingFactory wicFactory = new WICImagingFactory();
var wicBitmap = wicFactory.CreateBitmapFromMemory(
    (uint)bitmap.PixelWidth,
    (uint)bitmap.PixelHeight,
    new Guid(Imaging.PixelFormat.Format32bppBGRA),
    (uint)(bitmap.PixelWidth * 4),
    (uint)bitmap.PixelWidth * (uint)bitmap.PixelHeight * 4,
    bitmap.PixelBuffer.ToArray());

Now, you have a WIC bitmap (wicBitmap) that you can use for further processing or saving.

Remember to release resources when you're done using the WIC bitmap by calling the Release method on the wicBitmap object.

Note: The above code snippets assume you're working in C# with the Windows Runtime APIs and have the necessary references imported.