我有C#中的位图.我需要对图像进行操作.例如灰度zoom 、在图像上添加文本等.
我在Stackoverflow中找到了灰度函数,它接受位图并返回位图.
所以我需要将BitmapImage转换成Bitmap,做操作然后再转换回来.
我怎么才能做到这一点呢?这是最好的方法吗?
我有C#中的位图.我需要对图像进行操作.例如灰度zoom 、在图像上添加文本等.
我在Stackoverflow中找到了灰度函数,它接受位图并返回位图.
所以我需要将BitmapImage转换成Bitmap,做操作然后再转换回来.
我怎么才能做到这一点呢?这是最好的方法吗?
没有必要使用 foreign 图书馆.
将位图图像转换为位图:
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);
}
}
要将位图转换回BitmapImage,请执行以下操作:
[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;
}