using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Interop; using System.Windows.Media.Imaging; namespace ShrlAlgo.Toolkit.Core.Extensions; public static class ImageExtensions { /// /// 提取资源 /// /// /// public static void ExtractResource(string resourceName, string path) { using var manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); using var stream = File.Create(path); var array = new byte[8192]; int count; while ((count = manifestResourceStream.Read(array, 0, array.Length)) > 0) { stream.Write(array, 0, count); } } /// /// 资源管理器缩略图读取 /// /// /// /// /// public static BitmapSource LoadFileImage(string filename, int width, int height) { var bm = WindowsThumbnailProvider.GetThumbnail(filename, width, height, ThumbnailOptions.None); return Imaging.CreateBitmapSourceFromHBitmap(bm.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } /// /// 位图转图片 /// /// /// /// public static BitmapImage ToBitmapImage(this Bitmap bitmap) { if (bitmap is null) { throw new ArgumentNullException(nameof(bitmap)); } using var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Png); ms.Position = 0; var result = new BitmapImage(); result.BeginInit(); result.StreamSource = ms; result.CacheOption = BitmapCacheOption.OnLoad; result.EndInit(); return result; } /// /// 位图转像素集 /// /// /// /// public static BitmapSource ToBitmapSource(this Bitmap bitmap) { if (bitmap == null) { throw new ArgumentNullException(nameof(bitmap)); } return Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } /// /// Icon转BitmapSource /// /// /// public static BitmapSource ToBitmapSource(this Icon icon) { return Imaging.CreateBitmapSourceFromHIcon( icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromWidthAndHeight(icon.Width, icon.Height) ); } }