将BitmapImage转换为Bitmap,反之亦然(Converting BitmapImage to Bitmap and vice versa)
我在C#中有BitmapImage。 我需要做图像操作。 例如灰度调整,在图像上添加文本等
我在Stackoverflow中找到了接受Bitmap并返回Bitmap的灰度调用功能。
所以我需要将BitmapImage转换为Bitmap,然后进行操作和转换。
我该怎么做? 这是最好的方法吗?
I have BitmapImage in C#. I need to do operations on image. For example grayscaling, adding text on image, etc.
I have found function in stackoverflow for grayscaling which accepts Bitmap and returns Bitmap.
So I need to convert BitmapImage to Bitmap, do operation and convert back.
How can I do this? Is this best way?
最满意答案
没有必要使用外国图书馆。
将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); } }要将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; }There is no need to use foreign libraries.
Convert a BitmapImage to Bitmap:
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); } }To convert the Bitmap back to a 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; }
更多推荐
发布评论