Windows Phone 7 Bitmap编码
Windows Phone 7为图片的编码解码提供了高度灵活的、托管的API。方法如下:
1.利用WriteableBitmap类更新并渲染已有的bitmap(除非它是protected的)
2.利用Extensions.SaveJpeg方法将WriteableBitmap对象编码成一个JPEG流
该方法带有设置目标JPEG文件宽度和高度的参数,其语法如下:
public static void SaveJpeg(
this WriteableBitmap bitmap,
Stream targetStream,
int targetWidth,
int targetHeight,
int orientation,
int quality
)
下面是一个在WP7中将image编码解码的例子:
· 将WriteableBitmap对象编码成一个JPEG流,并将其添加到Picture Library中
· 将JPEG流解码成一个WriteableBitmap对象
首先,创建一个Windows Phone Application,在MainPage.xaml里添加一个Image控件。
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Image x:Name="img" Height="300" Stretch="None"/>
</StackPanel>
我们在按钮点击事件中将一个JPEG型图片解码成WriteableBitmap对象,
<Button x:Name="btnLoad" Content="Load Image" Click="btnLoad_Click"/>
后台代码如下:
private void btnLoad_Click(object sender, RoutedEventArgs e)
{//为JPEG文件创建一个流
StreamResourceInfo sri = null;
//注意,此时应将f1.jpg的Build Action设为Content
Uri jpegUri = new Uri("fl.jpg", UriKind.Relative);
         sri = Application.GetResourceStream(jpegUri);//将该流解码
                          WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(sri.Stream);         img.Source = bitmap;}下面,我们将WriteableBitmap对象编码成一个JPEG流。
<StackPanel x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Image x:Name="img" Height="300" Stretch="None"/>
<Button x:Name="btnLoad" Content="Load Image" Click="btnLoad_Click"/>
<Button x:Name="btnSave" Content="Save Image" Click="btnSave_Click"/>
</StackPanel>
以下代码是将图片保存到Picture Library中:
private void btnSave_Click(object sender, RoutedEventArgs e)
{// 在独立存储中为JPEG文件创建一个文件名。
String tempJPEG = "fl.jpg";
// 创建虚拟存储和文件流,确保tempJPEG唯一。
         var store = IsolatedStorageFile.GetUserStoreForApplication();if (store.FileExists(tempJPEG))
         {                 store.DeleteFile(tempJPEG);         }         IsolatedStorageFileStream fileStream = store.CreateFile(tempJPEG);StreamResourceInfo sri = null;
Uri uri = new Uri("fl.jpg", UriKind.Relative);
         sri = Application.GetResourceStream(uri);BitmapImage bitmap = new BitmapImage();
         bitmap.SetSource(sri.Stream);WriteableBitmap wb = new WriteableBitmap(bitmap);
//将 WriteableBitmap 对象编码成JPEG 流。
                          Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);                          fileStream.Close();// 从独立存储中创建一个新的流,并将该JPEG文件存储到Windows Phone的媒体库中。
                          fileStream = store.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);MediaLibrary mediaLibrary = new MediaLibrary();
Picture pic = mediaLibrary.SavePicture("savedflimage.jpg", fileStream);
                          fileStream.Close();}    注意:为了使用MediaLibrary,我们需要添加Microsoft.XNA.Framework引用。
这里,为了清楚查看我们所保存的JPEG文件,使用PhotoChooserTask:
private void btnPhotoChooser_Click(object sender, RoutedEventArgs e)
{PhotoChooserTask photoChooserTask = new PhotoChooserTask();
         photoChooserTask.Show();} 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号