在实际开发中时常遇到“Bitmap”转换为“BitmapImage”,“Bitmap”转换成“BitmapSource”格式转化的开发,特此记录。
1、“Bitmap”转换为“BitmapImage”
要将 System.Drawing.Bitmap 转换为 System.Windows.Media.Imaging.BitmapImage,我们可以首先将 Bitmap 保存到内存流中,然后使用该流来初始化一个 BitmapImage。以下是一个封装好的函数,实现了这一转换过程:
步骤 1:添加必要的引用
确保你的项目引用了 PresentationCore、WindowsBase 和 System.Drawing 程序集。PresentationCore 和 WindowsBase 通常在创建WPF应用程序时自动引用,但可能需要手动添加对 System.Drawing 的引用。
步骤 2:转换函数
using System;
using System.Drawing; // 引用 System.Drawing
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging; // 引用 PresentationCorepublic static BitmapImage ConvertBitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{if (bitmap == null)throw new ArgumentNullException(nameof(bitmap));using (MemoryStream memoryStream = new MemoryStream()){// 将 Bitmap 保存到内存流bitmap.Save(memoryStream, ImageFormat.Png);// 重置流的位置memoryStream.Position = 0;// 创建 BitmapImage 并从内存流加载BitmapImage bitmapImage = new BitmapImage();bitmapImage.BeginInit();bitmapImage.CacheOption = BitmapCacheOption.OnLoad; // 设置缓存选项bitmapImage.StreamSource = memoryStream;bitmapImage.EndInit();bitmapImage.Freeze(); // 冻结对象,使其不可修改return bitmapImage;}
}
说明:
- 这个方法首先检查传入的 System.Drawing.Bitmap 对象是否为 null。
- 使用 MemoryStream 作为临时存储,通过调用 bitmap.Save(memoryStream, ImageFormat.Png) 将 Bitmap 保存到内存流中。这里使用 PNG
格式是因为它支持透明度,并且是无损的,但你可以根据需要选择其他格式。- 设置内存流的 Position 为 0 是必要的,因为保存图像后,流的当前位置在末尾,直接读取会导致读取不到数据。
- 接下来,创建一个 BitmapImage 对象,并通过设置 StreamSource 为我们的内存流来加载图像数据。使用 BeginInit() 和 EndInit() 来开始和结束初始化过程。
- 设置 CacheOption 为 BitmapCacheOption.OnLoad 是为了在加载时将图像数据缓存,这样就可以释放内存流而不影响 BitmapImage。
- 调用 Freeze() 方法使 BitmapImage 对象不可修改,这是在WPF中处理图像时的最佳实践,特别是当你在非UI线程中操作图像时。
通过上述步骤,你可以将 System.Drawing.Bitmap 对象转换为WPF中使用的 System.Windows.Media.Imaging.BitmapImage 对象,从而在WPF应用程序中显示或进一步处理图像。
2、“Bitmap”转换成“BitmapSource”
在.NET Framework中,System.Drawing.Bitmap和System.Windows.Media.Imaging.BitmapSource是两个不同的图像表示方式。如果你需要将一个System.Drawing.Bitmap转换为System.Windows.Media.Imaging.BitmapSource,你可以使用以下代码实现:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;public static BitmapSource ConvertBitmapToBitmapSource(Bitmap bitmap)
{if (bitmap == null)return null;var memoryStream = new MemoryStream();bitmap.Save(memoryStream, ImageFormat.Bmp);memoryStream.Position = 0;var bitmapImage = new BitmapImage();bitmapImage.BeginInit();bitmapImage.StreamSource = memoryStream;bitmapImage.CacheOption = BitmapCacheOption.OnLoad;bitmapImage.EndInit();return bitmapImage;
}
说明
- 如果传入的Bitmap对象是null,那么函数会立即返回null。
- 首先,我们创建一个MemoryStream对象来存储Bitmap的数据。然后,我们调用Save方法将位图保存到内存流中,格式为bmp。
- 然后,我们将内存流的位置设为0,以便从流的开始位置读取数据。
- 接下来,我们创建一个新的BitmapImage,并使用BeginInit方法开始初始化过程。我们设置StreamSource属性为前面创建的内存流,并使用BitmapCacheOption.OnLoad选项缓存整个位图。
- 最后,我们调用EndInit方法完成初始化,并返回转换后的BitmapSource对象。
这个函数将一个System.Drawing.Bitmap转换为一个System.Windows.Media.Imaging.BitmapSource对象。你可以在需要时将其放入WPF应用程序中。