我在 C# 中有 BitmapImage。我需要对图像进行操作。例如灰度化、在图像上添加文本等。
我在 stackoverflow 中找到了接受位图并返回位图的灰度函数。
所以我需要将BitmapImage转换成Bitmap,进行运算再转换回来。
我该怎么做?这是最好的方法吗?
最佳答案
无需使用国外库
将 BitmapImage 转换为位图:
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
// BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));
using(MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
return new Bitmap(bitmap);
}
}
将位图转换回位图图像:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapImage retval;
try
{
retval = (BitmapImage)Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(hBitmap);
}
return retval;
}
关于c# - 将 BitmapImage 转换为位图,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484357/