将图像源设置为URI
如果我有一个在线图像的链接,我想将图像源设置为这个uri,我该如何做到最好? 我正在尝试的代码如下所示。
BitmapImage imgSource = new BitmapImage();
imgSource.UriSource = new Uri(movie.B_Poster, UriKind.Relative);
Poster.Source = imgSource;
此外,如果我想缓存此图像再次加载它是如何完成的?
谢谢
这是正确的方法。 如果要缓存映像以供以后重复使用,可以始终在隔离存储中下载它。 将WebClient
与OpenReadAsync
– 传递图像URI并将其存储在本地。
WebClient client = new WebClient(); client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted); client.OpenReadAsync(new Uri("IMAGE_URL")); void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication(); using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Create, file)) { byte[] buffer = new byte[1024]; while (e.Result.Read(buffer, 0, buffer.Length) > 0) { stream.Write(buffer, 0, buffer.Length); } } }
阅读它将是另一种方式:
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("image.jpg", System.IO.FileMode.Open, file)) { BitmapImage image = new BitmapImage(); image.SetSource(stream); image1.Source = image; }
你做得对了。
要缓存图像,您可以使用WebClient
(最简单)或使用WebRequest
– WebResponse
机制将其下载到本地文件存储。 然后,下次去设置图像位置时,检查它是否存在于本地。 如果是这样,请将其设置为本地文件。 如果没有,请将其设置为远程文件并下载。
PS。 您需要跟踪这些并删除旧文件,否则您将很快填满手机的内存。
在代码隐藏中设置图像源的方式绝对没问题。 另一种方法是,如果您使用绑定/ MVVM,则使用转换器将字符串URL转换为图像源:
public class StringToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string url = value as string; Uri uri = new Uri(url); return new BitmapImage(uri); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }
- 如何使用WiX Burn MBA捆绑包在MajorUpgrade期间检测当前安装的function?
- 如何在C#中将两个数组作为键和值互相放置?
- C#中的Char.IsHex()
- Log4net LogicalThreadContext未按预期工作
- 在sql中查询数据字典的最佳方法
- 如何处理xUnit .net的Assert.Throws 中的Tasks抛出的exception?
- AutomationElement使用Inspect.exe显示,但在使用UIAutomationCore.dll或System.Windows.Automation时不显示
- visual studio 2005设计师移动控件和调整窗体大小
- System。*引入NETStandard.Library依赖时引用的麻烦