gpt4 book ai didi

c# - 将 "large"数据流设置为 BitmapImage 的源时出错

转载 作者:太空宇宙 更新时间:2023-11-03 16:01:03 24 4
gpt4 key购买 nike

我使用缓存机制,将图像保存到独立存储并在下次加载它,尤其是在没有互联网连接的情况下。但是,它适用于小图像,但不适用于大约 200kb 的“大”图像。

这是我的代码:

public static object ExtractFromLocalStorage(Uri imageFileUri, string imageStorageFolder)
{
var isolatedStoragePath = GetFileNameInIsolatedStorage(imageFileUri, imageStorageFolder);

MemoryStream dataStream;
using (var fileStream = Storage.OpenFile(isolatedStoragePath, FileMode.Open, FileAccess.Read))
{
if (fileStream.Length > int.MaxValue)
return null;
dataStream = new MemoryStream((int)fileStream.Length);
var buffer = new byte[4096];
while (dataStream.Length < fileStream.Length)
{
var readCount = fileStream.Read(buffer, 0, Math.Min(buffer.Length, (int)(fileStream.Length - dataStream.Length)));
if (readCount <= 0)
{
throw new NotSupportedException();
}
dataStream.Write(buffer, 0, readCount);
}
}
var bi = new BitmapImage();
Deployment.Current.Dispatcher.BeginInvoke(() => bi.SetSource(dataStream));
return bi;
}

小图像工作正常,但当 bi.SetSource 被调用时,当加载这样的 200kb+ 图像时,我得到以下异常: 找不到该组件。 (HRESULT 异常:0x88982F50)

我能做些什么吗? 200kb 不算太大,文件保存完好并存在于本地。我希望有人能帮助我,因为它是我应用程序的最后一站......:/

编辑(1 月 31 日):

我重新开始,使用 KawagoeToolkit 库,我通过必要的方法为我的应用程序扩展了该库。它运行良好,但我仍然想知道为什么上面给出了这样一个奇怪的异常。

最佳答案

不要在不必要时使用调度程序。它将介绍闭包语义。在您的方法中,即使您处于另一个同步上下文中,它也没有意义。因为不涉及 GUI 线程。

无论如何,我测试了您的代码,但有一点不同 - 我使用的是 StorageFile 而不是 IsolatedStorage。而且效果很好。

    private async void Button_Click(object sender, RoutedEventArgs e)
{
//622Kb: http://www.nasa.gov/sites/default/files/styles/1920x1080_autoletterbox/public/pia17147.jpg?itok=6jErm40V
//2.7Mb: http://www.nasa.gov/sites/default/files/304_lunar_transit_14-00_ut_0.jpg
StorageFile imageFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\test3.jpg");
MemoryStream mz;
using (var z = await imageFile.OpenStreamForReadAsync())
{
if (z.Length > int.MaxValue) return;
mz = new MemoryStream((int)z.Length);
var buffer = new byte[4096];

while (mz.Length < z.Length)
{
var readCount = z.Read(buffer, 0, Math.Min(buffer.Length, (int)(z.Length - mz.Length)));
if (readCount <= 0)
{
throw new NotSupportedException();
}
mz.Write(buffer, 0, readCount);
}
}

var bmp = new BitmapImage();
bmp.SetSource(mz);
//Deployment.Current.Dispatcher.BeginInvoke(() => img.Source = bmp); // if in another sync context only
img.Source = bmp;
}

关于c# - 将 "large"数据流设置为 BitmapImage 的源时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21386742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com