整理代码
This commit is contained in:
83
ShrlAlgoToolkit.RevitAddins/Extensions/ImageExtensions.cs
Normal file
83
ShrlAlgoToolkit.RevitAddins/Extensions/ImageExtensions.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace ShrlAlgoToolkit.RevitAddins.Extensions;
|
||||
|
||||
public static class ImageExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 位图转图片
|
||||
/// </summary>
|
||||
/// <param name="bitmap"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentNullException"></exception>
|
||||
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;
|
||||
}
|
||||
/// <summary>
|
||||
/// 位图转像素集
|
||||
/// </summary>
|
||||
/// <param name="bitmap"></param>
|
||||
/// <returns></returns>
|
||||
public static BitmapSource ToBitmapSource(this Bitmap bitmap)
|
||||
{
|
||||
return bitmap == null
|
||||
? null
|
||||
: Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Icon转BitmapSource
|
||||
/// </summary>
|
||||
/// <param name="icon"></param>
|
||||
/// <returns></returns>
|
||||
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)
|
||||
);
|
||||
}
|
||||
public static ImageSource ConvertBitmapToImageSource(this Bitmap bitmap)
|
||||
{
|
||||
using (MemoryStream memory = new MemoryStream())
|
||||
{
|
||||
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
|
||||
memory.Position = 0;
|
||||
BitmapImage bitmapImage = new BitmapImage();
|
||||
bitmapImage.BeginInit();
|
||||
bitmapImage.StreamSource = memory;
|
||||
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
|
||||
bitmapImage.EndInit();
|
||||
return bitmapImage;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user