转载自: http://www.zdave.net/archives/369:
保存图片到隔离存储空间
示例中首先检查文件是否已经存在,然后把图片保存到隔离存储空间(转换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控件中呈现出来。
1
2
3
4
5
6
7
8
9
10
11
12
|
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。
示例中从隔离存储空间中读取一个图片,然后保存到手机的媒体库中。
1
2
3
4
5
6
7
8
9
10
11
12
|
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();
|