Files
29WxOrder/29WxOrderWpf/Converters/ImageUrlToBitmapImageConverter.cs
T

81 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using Work;
namespace _29WxOrderWpf.Converters
{
public class ImageUrlToBitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string url && Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
try
{
// 直接加载绑定如果遇到有问题的网络图片会直接崩溃。
//var bitMap = new BitmapImage(new Uri(url));
BitmapImage bitMap = null;
//bitMap = LoadImageFromUrl(url + "?imageView2/1/w/100/format/webp|imageMogr2/auto-orient=");
bitMap = LoadImageFromUrl(url);
return bitMap;
//string errStr = "";
//var bitmapImg = GetUrlImg(url, out errStr);
//return bitmapImg;
}
catch
{
}
//return Task.Run(() => new BitmapImage(new Uri(url))); // 使用 Task.Run 来异步加载图片。
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException(); // 不需要反向转换,所以不实现。
}
public static BitmapImage LoadImageFromUrl(string url)
{
BitmapImage bitmap = new BitmapImage();
try
{
using (WebClient webClient = new WebClient())
{
// 下载图片数据到内存流
using (MemoryStream stream = new MemoryStream(webClient.DownloadData(url)))
{
stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit();
bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze(); // 防止后续更改,提高性能
}
}
}
catch (Exception ex)
{
// 处理异常,例如打印错误信息或设置一个默认图片等
//Console.WriteLine("Error loading image: " + ex.Message);
return null;
}
return bitmap;
}
}
}