如何清除WriteableBitmap的内存

时间:2014-10-13 14:01:23

标签: c# image windows-phone-8 writablebitmap

我正在使用PhotoChooserTask从图库中选择图片,这是我的设置

private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
    PhotoChooserTask photo = new PhotoChooserTask();
    photo.Completed += photo_Completed;
    photo.Show();
}

void photo_Completed(object sender, PhotoResult e)
{
    if (e.ChosenPhoto != null)
    {
        WriteableBitmap wbmp1 = PictureDecoder.DecodeJpeg(e.ChoosenPhoto, (int)scrnWidth, (int)scrnHeight);
        ImageBrush iBru = new ImageBrush();
        iBru.ImageSource = wbmp1;
        iBru.Stretch = Stretch.Fill;
        ContentPanel.Background = iBru;
    }
}

问题:这种方式只适用于.JPEG张图片

让它与其他image formats一起使用,我尝试了这个:

void photo_Completed(object sender, PhotoResult e)
{
    if (e.ChosenPhoto != null)
    {
        WriteableBitmap wBmp = new WriteableBitmap(0, 0);//6930432
        wBmp.SetSource(e.ChosenPhoto);//23105536
        MemoryStream tmpStream = new MemoryStream();//23105536
        wBmp.SaveJpeg(tmpStream, (int)scrnWidth, (int)scrnHeight, 0, 100);//22831104
        tmpStream.Seek(0, SeekOrigin.Begin);//22831104

        WriteableBitmap wbmp1 = PictureDecoder.DecodeJpeg(tmpStream, (int)scrnWidth, (int)scrnHeight);//24449024
        ImageBrush iBru = new ImageBrush();//24449024
        iBru.ImageSource = wbmp1;//24449024
        iBru.Stretch = Stretch.Fill;
        ContentPanel.Background = iBru;
    }
}

这种方式适用于不同的图像格式,但它不具有内存效率。

我已经提到每行后使用的bytes数量,以便更好地理解。

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

2 个答案:

答案 0 :(得分:4)

@Soonts建议我使用BitmapImage并解决了我的目的,

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

耗材少memory我们可以scale向下image

答案 1 :(得分:2)

摆脱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;
相关问题