【问题标题】:Load a PNG from isolated storage on Windows Phone从 Windows Phone 上的独立存储加载 PNG
【发布时间】:2014-02-15 21:20:50
【问题描述】:

我可以使用专门的 JPEG 加载 jpeg 方法很好地加载 JPEG,我也可以使用 SO 中详述的许多方法很好地保存 PNG。

但是,每当我创建用于从独立存储加载 PNG 的流时,它都会导致 BitmapImage 的大小为零。

这就是我所拥有的......

public static async Task<BitmapImage> ReadBitmapImageFromIsolatedStorage(string fn)
{

        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        if (local != null)
        {
            Stream file = await local.OpenStreamForReadAsync(fn);
            BitmapImage bi = new BitmapImage();
            bi.SetSource(file);
            return bi;

        }

        return null;

}

我也尝试了很多变化。在创建 BitmapImages 时读取流似乎存在某种延迟,这意味着流通常在 BitmapImage 读取它之前就被处理掉了。 WPF中有一个选项可以设置,但是WINdows Phone BitmapImage没有这个选项。

【问题讨论】:

标签: windows-phone-8


【解决方案1】:

试试这个:

BitmapImage image = new BitmapImage();
image.DecodePixelWidth = 500; //desired width, optional
image.DecodePixelHeight = 500; //desired height, optional

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (myIsolatedStorage.FileExists("imagepath"))
    {
        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("imagepath", FileMode.Open, FileAccess.Read))
        {
            image.SetSource(fileStream);
        }
    }
}

【讨论】:

  • 除非DecodePixel[Width|Height] 有所作为,否则它不起作用。仅在最后几次尝试中,我才更改为新的Windows.Storage 方法...
【解决方案2】:

这就是我发现最终使用新的Windows.Storage API 的工作

我不是 100% 清楚最初的问题是什么,但这是可行的。这有一些额外的功能,如果它无法读取,它会稍后重试...

public static async Task<BitmapImage> ReadBitmapImageFromIsolatedStorage(string fn)
    {
        Uri uri = new Uri(String.Format("ms-appdata:///local/{0}", fn));
        // FileAccessAttempts is just an int that determines how many time 
        // to try reading before giving up
        for (int i = 0; i < AppConfig.FileAccessAttempts; i++)
        {
            try
            {
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
                Stream stream = await file.OpenStreamForReadAsync();
                BitmapImage bi = new BitmapImage();
                bi.SetSource(stream);
                return bi;
            }
            catch
            {
                // Similar functions also have a ~1 second retry interval so introduce
                // a random element to prevent blocking from accidentally synched retries
                Random r = new Random();
                System.Threading.Thread.Sleep(950 + (int)Math.Floor(r.Next() * 50.0));
            }
        }
        return new BitmapImage();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多