从Windows Phone 7上的隔离存储打开JPEG时出现问题

脚本

  1. 应用程序打开
  2. 检查隔离存储中是否存在背景图像
  3. 如果没有,请从Web下载,并将其保存到隔离存储
  4. 从Isolated Storage中加载图像并将其设置为Panorama控件上的Background

问题

图像未加载到GUI中。当我检查从隔离存储器接收的字节数组时,它包含与最初写入的字节数相同的字节数,但图像未显示。

这是我正在尝试找出问题的一些测试代码:

using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!appStorage.FileExists(@"default.jpg")) { BitmapImage bmp = sender as BitmapImage; byte[] bytes = bmp.ConvertToBytes(); using (var inputfile = appStorage.CreateFile(@"default.jpg")) { inputfile.Write(bytes, 0, bytes.Length); } } using (var isfs = appStorage.OpenFile(@"default.jpg", FileMode.OpenOrCreate, FileAccess.Read)) { BitmapImage bmp = new BitmapImage(); bmp.SetSource(isfs); MainPanorama.Background = new ImageBrush { Opacity = 0.4, Stretch = Stretch.None, ImageSource = bmp }; } } 

如果sender是来自其他来源的加载图像,我已尝试在MainPanorama-control上将发件人设置为backgroundimage,这样就可以了。 所以问题在于从隔离存储加载。

有任何想法吗?

编辑:这听起来像是时间或随机访问流的问题。

你可以尝试的事情:

  1. 尝试将整个映像加载到内存数组中 – 一个MemoryStream – 然后在SetSource调用中使用它

  2. 尝试删除未使用的代码 – .ImageOpened委托和img = new Image()调用

  3. 如果那些东西没有帮助,那么尝试在字节级别检查两个流。

有关1的更多信息,请参阅如何从隔离存储加载映像并在设备上显示它? – 请注意,这是Microsoft的支持官方示例,它将图像加载到内存MemoryStream中,然后在屏幕上的Image中使用它。

微软的代码:

 // The image will be read from isolated storage into the following byte array byte [] data; // Read the entire image in one go into a byte array using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { // Open the file - error handling omitted for brevity // Note: If the image does not exist in isolated storage the following exception will be generated: // System.IO.IsolatedStorage.IsolatedStorageException was unhandled // Message=Operation not permitted on IsolatedStorageFileStream using (IsolatedStorageFileStream isfs = isf.OpenFile("WP7Logo.png", FileMode.Open, FileAccess.Read)) { // Allocate an array large enough for the entire file data = new byte[isfs.Length]; // Read the entire file and then close it isfs.Read(data, 0, data.Length); isfs.Close(); } } // Create memory stream and bitmap MemoryStream ms = new MemoryStream(data); BitmapImage bi = new BitmapImage(); // Set bitmap source to memory stream bi.SetSource(ms); // Create an image UI element – Note: this could be declared in the XAML instead Image image = new Image(); // Set size of image to bitmap size for this demonstration image.Height = bi.PixelHeight; image.Width = bi.PixelWidth; // Assign the bitmap image to the image's source image.Source = bi; // Add the image to the grid in order to display the bit map ContentPanel.Children.Add(image); 

请报告修复它的内容。

我的猜测是这是一个时间问题。 在UI准备好显示图像之前,是否会调用此代码? 如果可视树未完全加载,我不确定在设置图像源时会发生什么。

尝试类似这样的伪代码:

MyPage() { this.Loaded += () => YourImageLoadMethod; InitializeComponent(); }