System.Drawing.BitmapとSystem.Windows.Media.ImageSourceの相互変換の方法を紹介します。
以下に紹介する方法でBitmapとImageSourceの相互変換が出来ますが、変換したイメージが若干荒くなる気がします。
左が変換前、右が変換後です。
もっと良い方法があれば教えていただけると助かります。
ImageSourceからBitmapに変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
/// <summary> /// BitmapSourceをBitmapに変換します。 /// </summary> /// <param name="bitmapSource">変換するBitmapSourceオブジェクト。</param> /// <returns></returns> public static Bitmap ToBitmap(BitmapSource bitmapSource) { if (bitmapSource == null) return null; var bitmap = new Bitmap( bitmapSource.PixelWidth, bitmapSource.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); var bitmapData = bitmap.LockBits( new Rectangle(System.Drawing.Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); bitmapSource.CopyPixels( Int32Rect.Empty, bitmapData.Scan0, bitmapData.Height * bitmapData.Stride, bitmapData.Stride ); bitmap.UnlockBits(bitmapData); return bitmap; } |
BitmapからImageSourceに変換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class NativeMethods { [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); } /// <summary> /// BitmapをImageSourceに変換します。 /// </summary> /// <param name="bmp">変換するBitmapオブジェクト。</param> /// <returns></returns> public static ImageSource ToImageSource(Bitmap bmp) { if (bmp == null) return null; var hBitmap = bmp.GetHbitmap(); try { return Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Exception) { return null; } finally { NativeMethods.DeleteObject(hBitmap); } } |
コメント