Files
ShrlAlgoToolkit/Sai.Toolkit.Revit/Assist/ImageAssist.cs

76 lines
1.8 KiB
C#
Raw Normal View History

2024-09-22 11:05:41 +08:00
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 Sai.Toolkit.Revit.Assist;
public static class ImageAssist
{
/// <summary>
/// 解压资源
/// </summary>
/// <param name="resourceName"></param>
/// <param name="path"></param>
public static void ExtractResource(string resourceName, string path)
{
using var manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using Stream 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 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)
{
2024-10-08 16:21:39 +08:00
return bitmap == null
? null
: Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
2024-09-22 11:05:41 +08:00
2024-10-08 16:21:39 +08:00
/// <summary>
/// Icon转BitmapSource
/// </summary>
/// <param name="icon"></param>
/// <returns></returns>
public static BitmapSource ToBitmapSource(this Icon icon)
2024-09-22 11:05:41 +08:00
{
return Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
new Int32Rect(0, 0, icon.Width, icon.Height),
BitmapSizeOptions.FromWidthAndHeight(icon.Width, icon.Height)
);
}
}