2

I am picking image from gallery using PhotoChooserTask, here is my setup

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;
    }
}

Problem: with this way is it works only with .JPEG images

to make it work with other image formats, I tried this:

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;
    }
}

this way works with different image formats, but it is not memory efficient.

I have mentioned number of bytes used after each line for better understanding.

Question: In latter code snippet, I do not need wbmp anymore, How can I clear memory used by wbmp object?

Dev
  • 1,130
  • 10
  • 21

2 Answers2

4

As @Soonts suggested I used BitmapImage and it solves my purpose,

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

It consumes less memory and we can scale down image

Dev
  • 1,130
  • 10
  • 21
2

Get rid of the WriteableBitmap, instead do something like this:

var bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource( e.ChosenPhoto );
var ib = new ImageBrush() { ImageSource = bmp, Stretch = Stretch.Fill };
ContentPanel.Background = ib;
Soonts
  • 20,079
  • 9
  • 57
  • 130