优化图片显示

This commit is contained in:
wule committed 2026-10-19 14:22:25 +08:00
1 parent 1d4867ebf2
commit 17728c074c
3 files changed
+101 -15

No files matched your search

+83 -1
View File
@@ -1,11 +1,14 @@
using System;
using CefSharp.DevTools.IO;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
@@ -423,6 +426,85 @@ namespace AllBase
return bitmap;
}
public static async Task<BitmapImage> LoadBitmipImageFromUrlAsync(string url, int? width = null, int? height = null)
{
BitmapImage bitmap = new BitmapImage();
try
{
//using (WebClient webClient = new WebClient())
//{
//webClient.DownloadDataCompleted += (sender, e) =>
//{
// if (e.Cancelled)
// {
// //Console.WriteLine("下载已取消");
// bitmap = null;
// }
// else if (e.Error != null)
// {
// //Console.WriteLine("下载出错: " + e.Error.Message);
// bitmap = null;
// }
// else
// {
// byte[] data = (byte[])e.Result;
// //string text = System.Text.Encoding.UTF8.GetString(data);
// //Console.WriteLine(text);
// // 下载图片数据到内存流
// using (MemoryStream stream = new MemoryStream(data))
// {
// stream.Position = 0; // 重置流的位置到开始处
// bitmap.BeginInit();
// if (width != null && height != null)
// {
// bitmap.DecodePixelWidth = width.Value;
// bitmap.DecodePixelHeight = height.Value;
// }
// bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
// bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
// bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
// bitmap.StreamSource = stream;
// bitmap.EndInit();
// bitmap.Freeze(); // 防止后续更改,提高性能
// }
// }
//};
//await webClient.DownloadDataAsync(new Uri(url));
//}
using (HttpClient client = new HttpClient())
{
// 下载图片数据到内存流
using (MemoryStream stream = new MemoryStream(await client.GetByteArrayAsync(url)))
{
stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit();
if (width != null && height != null)
{
bitmap.DecodePixelWidth = width.Value;
bitmap.DecodePixelHeight = height.Value;
}
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;
}
//public string BitmapImageToBase64(BitmapImage bitmapImage)
//{