iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐕

Best Practices for Converting BitmapSource to Bitmap

に公開

Introduction

When developing image processing-related applications in WPF, mutual conversion between Bitmap and BitmapSource occurs frequently.

Here, I have organized the best practices for converting from BitmapSource to Bitmap.

Best Practice

The best way is to create BitmapData from a Bitmap and write it out from the BitmapSource using CopyPixels.

BitmapSource source = new BitmapImage(new Uri(new FileInfo("Color.jpg").FullName));

var bitmap = new Bitmap(
    source.PixelWidth,
    source.PixelHeight,
    PixelFormat.Format32bppPArgb);
var data = bitmap.LockBits(
    new Rectangle(Point.Empty, bitmap.Size),
    ImageLockMode.WriteOnly,
    PixelFormat.Format32bppPArgb);
try
{
    source.CopyPixels(
        Int32Rect.Empty,
        data.Scan0,
        data.Height * data.Stride,
        data.Stride);
    return bitmap;
}
finally
{
    bitmap.UnlockBits(data);
}

Don't forget UnlockBits.

Verification

This time, I evaluated the following three patterns:

  1. Using BitmapData (Best Practice)
  2. Saving to JPEG with BitmapEncoder and loading the Bitmap
  3. Saving to BMP with BitmapEncoder and loading the Bitmap

Copying via BitmapData showed good results in both processing speed and memory usage.

BitmapEncoder Code Example

BitmapSource source = new BitmapImage(new Uri(new FileInfo("Color.jpg").FullName));

using var outStream = new MemoryStream();
var enc = new JpegBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(source));
enc.Save(outStream);
return new Bitmap(outStream);

Discussion