C# 如何清除可写位图的内存

C# 如何清除可写位图的内存,c#,image,windows-phone-8,writablebitmap,C#,Image,Windows Phone 8,Writablebitmap,我正在使用PhotoChooserTask从图库中拾取图像,这是我的设置 private void应用程序BariconButton\u单击(对象发送方,事件参数e) { PhotoChooserTask photo=新的PhotoChooserTask(); 照片完成+=照片完成; photo.Show(); } 已完成作废照片(对象发送器、照片结果e) { 如果(e.ChosenPhoto!=null) { WriteableBitmap wbmp1=PicturedCoder.Decode

我正在使用
PhotoChooserTask
从图库中拾取图像,这是我的设置

private void应用程序BariconButton\u单击(对象发送方,事件参数e)
{
PhotoChooserTask photo=新的PhotoChooserTask();
照片完成+=照片完成;
photo.Show();
}
已完成作废照片(对象发送器、照片结果e)
{
如果(e.ChosenPhoto!=null)
{
WriteableBitmap wbmp1=PicturedCoder.DecodeJpeg(e.choosePhoto,(int)scrnWidth,(int)scrnHeight);
ImageBrush iBru=新的ImageBrush();
iBru.ImageSource=wbmp1;
iBru.Stretch=Stretch.Fill;
ContentPanel.Background=iBru;
}
}
问题:这种方法只能用于
.JPEG
图像

为了使其与其他
图像格式
配合使用,我尝试了以下方法:

void photo_已完成(对象发送方,PhotoResult e)
{
如果(e.ChosenPhoto!=null)
{
WriteableBitmap wBmp=新的WriteableBitmap(0,0);//6930432
wBmp.SetSource(e.ChosenPhoto);//23105536
MemoryStream tmpStream=新的MemoryStream();//23105536
SaveJpeg(tmpStream,(int)scrnWidth,(int)scrnHeight,01100);/22831104
tmpStream.Seek(0,SeekOrigin.Begin);/22831104
WriteableBitmap wbmp1=PictureDecoder.DecodeJpeg(tmpStream,(int)scrnWidth,(int)scrnHeight);//24449024
ImageBrush iBru=新建ImageBrush();//24449024
iBru.ImageSource=wbmp1;//24449024
iBru.Stretch=Stretch.Fill;
ContentPanel.Background=iBru;
}
}
这种方法适用于不同的图像格式,但内存效率不高

为了更好地理解,我提到了每行后面使用的
字节数


问题:在后面的代码片段中,我不再需要wbmp,如何清除wbmp对象使用的内存?

摆脱WriteableBitmap,改为执行以下操作:

var bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource( e.ChosenPhoto );
var ib = new ImageBrush() { ImageSource = bmp, Stretch = Stretch.Fill };
ContentPanel.Background = ib;

正如@Soons建议的那样,我使用了
BitmapImage
,它解决了我的问题

BitmapImage bmp = new BitmapImage();
bmp.DecodePixelWidth = (int)scrnWidth;
bmp.DecodePixelHeight = (int)scrnHeight;
bmp.SetSource(e.ChosenPhoto);

它消耗更少的
内存
,而且我们可以
向下缩放
图像

优点:这种方法既简单又干净。缺点:1)需要更多的内存,2)我们无法缩小规模,它怎么会需要太多内存?这两种方法都使用位图。