Files
29WxOrder/29WxOrderWpf/Converters/ImageUrlToBitmapImageConverter.cs
T
2026-08-21 14:15:16 +08:00

60 lines
1.9 KiB
C#

using System;
using System.Collections.Concurrent;
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
{
/// <summary> 缓存上限,防止大量缩略图重复下载导致内存膨胀 </summary>
private const int MaxCacheCount = 200;
private readonly ConcurrentDictionary<string, BitmapImage> _imageCache = new ConcurrentDictionary<string, BitmapImage>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string url && Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
if (_imageCache.TryGetValue(url, out BitmapImage cached))
{
return cached;
}
try
{
// 直接加载绑定如果遇到有问题的网络图片会直接崩溃。
BitmapImage bitMap = AllBase.ImageBuild.LoadBitmipImageFromUrl(url);
if (bitMap != null)
{
if (_imageCache.Count >= MaxCacheCount)
{
_imageCache.Clear();
}
_imageCache[url] = bitMap;
}
return bitMap;
}
catch
{
}
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException(); // 不需要反向转换,所以不实现。
}
}
}