You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.3 KiB
80 lines
2.3 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Media.Imaging;
|
|
|
|
namespace AIK.Common
|
|
{
|
|
public class ImageUtils
|
|
{
|
|
/// <summary>
|
|
/// 从文件路径加载图像(同步)
|
|
/// </summary>
|
|
public static BitmapImage LoadFromFile(string filePath)
|
|
{
|
|
var bitmap = new BitmapImage();
|
|
using (var stream = File.OpenRead(filePath))
|
|
{
|
|
bitmap.BeginInit();
|
|
bitmap.StreamSource = stream;
|
|
bitmap.CacheOption = BitmapCacheOption.OnLoad;
|
|
bitmap.EndInit();
|
|
}
|
|
return bitmap;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从字节数组加载图像
|
|
/// </summary>
|
|
public static BitmapImage LoadFromBytes(byte[] imageData)
|
|
{
|
|
using (var ms = new MemoryStream(imageData))
|
|
{
|
|
return StreamToBitmapImage(ms);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从任意Stream加载图像(不负责关闭流)
|
|
/// </summary>
|
|
public static BitmapImage StreamToBitmapImage(Stream stream)
|
|
{
|
|
if (stream.CanSeek) stream.Position = 0;
|
|
|
|
var bitmap = new BitmapImage();
|
|
bitmap.BeginInit();
|
|
bitmap.StreamSource = stream;
|
|
bitmap.CacheOption = BitmapCacheOption.OnLoad;
|
|
bitmap.EndInit();
|
|
return bitmap;
|
|
}
|
|
|
|
public static BitmapImage StreamToBitmapImageFull(Stream stream)
|
|
{
|
|
if (stream == null) return null;
|
|
try
|
|
{
|
|
if (stream.CanSeek) stream.Position = 0;
|
|
using var memoryStream = new MemoryStream();
|
|
stream.CopyTo(memoryStream);
|
|
memoryStream.Position = 0;
|
|
var bitmap = new BitmapImage();
|
|
bitmap.BeginInit();
|
|
bitmap.StreamSource = stream;
|
|
bitmap.CacheOption = BitmapCacheOption.OnLoad;
|
|
bitmap.EndInit();
|
|
bitmap.Freeze();
|
|
|
|
return bitmap;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|