Code

How To Convert Bitmap to BitmapImage

How To Convert System.Drawing.Bitmap to Microsoft.UI.Xaml.Media.Imaging.BitmapImage

// get bitmapimage
var bitmapImage = await ConvertBitmapToBitmapImage(app.AppIcon);


// determine bitmapimage not null
if (bitmapImage != null) {
// set app icon
appItem.AppIcon = bitmapImage;
}


Add the Function 'ConvertBitmapToBitmapImage':

// convert bitmap to bitmapimage
public static async TaskBitmapImage> ConvertBitmapToBitmapImage(System.Drawing.Bitmap bitmap) {
// determine bitmap not null
if (bitmap == null)
// return null
return null;

// create new bitmapimage
Microsoft.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new();

// create imagestream
var imageStream = new MemoryStream();

// using imagestream
using (imageStream) {
// save bitmap as jpeg
bitmap.Save(imageStream, ImageFormat.Jpeg);
imageStream.Position = 0;

// convert stream to bytes array
byte[] imageBytes = imageStream.ToArray();

// get bitmapimage from bytes
bitmapImage = await GetBitmapImageFromBitmapBytes(imageBytes);
}

// return bitmapimage
return bitmapImage;
}


Add the Function 'GetBitmapImageFromBitmapBytes':

// get bitmapimage from bitmap bytes
public static async TaskBitmapImage> GetBitmapImageFromBitmapBytes(byte[] data) {
// create new bitmapimage
Microsoft.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new();

// using memorystream
using (var stream = new InMemoryRandomAccessStream()) {
// using datawriter
using (var writer = new DataWriter(stream)) {
// write bytes
writer.WriteBytes(data);

// store
await writer.StoreAsync();

// flush
await writer.FlushAsync();

// detach
writer.DetachStream();
}

// set stream to 0
stream.Seek(0);

// set bitmapimage source from stream
await bitmapImage.SetSourceAsync(stream);
}

// return bitmapimage
return bitmapImage;
}