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 { /// /// 从文件路径加载图像(同步) /// 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; } /// /// 从字节数组加载图像 /// public static BitmapImage LoadFromBytes(byte[] imageData) { using (var ms = new MemoryStream(imageData)) { return StreamToBitmapImage(ms); } } /// /// 从任意Stream加载图像(不负责关闭流) /// 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; } } } }