WP7 Isolated Storage详解 读取、保存图片文件

来源:互联网 发布:京东店铺数据分析报告 编辑:程序博客网 时间:2024/05/18 01:39
首先创建一个Windows Phone 7项目,在项目中添加一个图片例如“logo.jpg”,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:
using System.IO.IsolatedStorage;using System.Windows.Media.Imaging;using System.IO;using System.Windows.Resources;using Microsoft.Xna.Framework.Media;using Microsoft.Phone.Tasks;

提示:Microsoft.Xna.Framework.Media;仅当你要把图片保存到媒体库的时候才需要添加引用。

对于很多应用,向隔离存储空间读取、保存图片文件是很常见的任务。在WP7中,你还可以保存、读取媒体库中的图片。

一般情况下我们使用类IsolatedStorageFileStream进行读、写、创建文件等操作。对于图片,最大的不同就是使用类BitmapImage和类WriteableBitmap.

保存图片到隔离存储空间

示例中首先检查文件是否已经存在,然后把图片保存到隔离存储空间(转换WriteableBitmap对象到JPEG stream)。

 

String tempJPEG = "logo.jpg";

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (myIsolatedStorage.FileExists(tempJPEG))
    {
        myIsolatedStorage.DeleteFile(tempJPEG);
    }

    IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);

    StreamResourceInfo sri = null;
    Uri uri = new Uri(tempJPEG, UriKind.Relative);
    sri = Application.GetResourceStream(uri);

    BitmapImage bitmap = new BitmapImage();
    bitmap.SetSource(sri.Stream);
    WriteableBitmap wb = new WriteableBitmap(bitmap);

    // Encode WriteableBitmap object to a JPEG stream.
    Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

    fileStream.Close();
}

 

提示:你也可以使用WriteableBitmap来保存图片:wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);

从隔离存储空间读取图片

示例中首先从隔离存储空间打开了一个名为logo.jpg的图片,并在一个Image控件中呈现出来。

 

BitmapImage bi = new BitmapImage();
 
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("logo.jpg", FileMode.Open, FileAccess.Read))
                {
                    bi.SetSource(fileStream);
                    this.img.Height = bi.PixelHeight;
                    this.img.Width = bi.PixelWidth;
                }
            }
            this.img.Source = bi;

提示:“img”是一个在MainPage.xaml中的图片控件:<Image x:Name="img"/>

保存图片到手机媒体库

访问MediaLibrary需要在项目中添加引用:Microsoft.XNA.Framework。

示例中从隔离存储空间中读取一个图片,然后保存到手机的媒体库中。

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("logo.jpg", FileMode.Open, FileAccess.Read))
                {
                    MediaLibrary mediaLibrary = new MediaLibrary();
                    Picture pic = mediaLibrary.SavePicture("SavedLogo.jpg", fileStream);
                    fileStream.Close();
                }
            }
 
            PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Show();

原创粉丝点击