【问题标题】:how to clear memory of WritableBitmap如何清除 WriteableBitmap 的内存
【发布时间】:2014-12-08 03:04:59
【问题描述】:

我正在使用 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 的数量。

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

【问题讨论】:

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


    【解决方案1】:

    摆脱 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;
    

    【讨论】:

    • 优点:这种方式既简单又干净。缺点:1)需要更多内存,2)我们无法缩小它
    • 怎么会占用太多内存呢?两种方法都使用位图。
    【解决方案2】:

    正如@Soonts 建议的那样,我使用了BitmapImage,它解决了我的目的,

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

    它消耗更少memory,我们可以scale down image

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多