83 lines
2.6 KiB
C#
83 lines
2.6 KiB
C#
using System;
|
|
using System.ComponentModel;
|
|
using System.Drawing;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
using System.Windows;
|
|
using System.Windows.Media.Imaging;
|
|
|
|
namespace JD.WinFormExtensions
|
|
{
|
|
public static class ImageExtensions
|
|
{
|
|
/// <summary>
|
|
/// FxCop requires all Marshalled functions to be in a class called NativeMethods.
|
|
/// </summary>
|
|
internal static class NativeMethods
|
|
{
|
|
[DllImport("gdi32.dll")]
|
|
[return: MarshalAs(UnmanagedType.Bool)]
|
|
internal static extern bool DeleteObject(IntPtr hObject);
|
|
}
|
|
|
|
public static Image ToImage(this System.Windows.Media.Imaging.BitmapSource image)
|
|
{
|
|
MemoryStream ms = new MemoryStream();
|
|
var encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
|
|
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(image));
|
|
encoder.Save(ms);
|
|
ms.Flush();
|
|
return Image.FromStream(ms);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts a <see cref="System.Drawing.Image"/> into a WPF <see cref="BitmapSource"/>.
|
|
/// </summary>
|
|
/// <param name="source">The source image.</param>
|
|
/// <returns>A BitmapSource</returns>
|
|
public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
|
|
{
|
|
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
|
|
|
|
var bitSrc = bitmap.ToBitmapSource();
|
|
|
|
bitmap.Dispose();
|
|
bitmap = null;
|
|
|
|
return bitSrc;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
|
|
/// </summary>
|
|
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
|
|
/// </remarks>
|
|
/// <param name="source">The source bitmap.</param>
|
|
/// <returns>A BitmapSource</returns>
|
|
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
|
|
{
|
|
BitmapSource bitSrc = null;
|
|
|
|
var hBitmap = source.GetHbitmap();
|
|
|
|
try
|
|
{
|
|
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
|
|
hBitmap,
|
|
IntPtr.Zero,
|
|
Int32Rect.Empty,
|
|
BitmapSizeOptions.FromEmptyOptions());
|
|
}
|
|
catch (Win32Exception)
|
|
{
|
|
bitSrc = null;
|
|
}
|
|
finally
|
|
{
|
|
NativeMethods.DeleteObject(hBitmap);
|
|
}
|
|
|
|
return bitSrc;
|
|
}
|
|
}
|
|
}
|