Tuesday, November 9, 2010

WritableBitmap to MemoryStream to MediaLibrary

I was reading about the MediaLibrary API when I decided to put my reading to work. Nothing fancy, just take a screenshot of the application and save it to media library.

Take a look at this code

WriteableBitmap wb = new WriteableBitmap(image1, new TranslateTransform());
myFileStream = new MemoryStream();
wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
myFileStream.Seek(0, SeekOrigin.Begin);
MediaLibrary library = new MediaLibrary();
Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
myFileStream.Close();


Most importantly is this piece of code:


myFileStream.Seek(0, SeekOrigin.Begin);


if you do not do this before you save to MediaLibrary, an exception will be thrown with an error message that goes something like "value out of range"...

Another pointer is to disconnect the device from Zune when you run this piece of code. Otherwise you will get an exception saying "Unexpected error has occur".

Really hope MS do something about this whole Zune thingy. It can be quite troublesome when it comes down to debugging.

*Update: Use Windows Phone Connect Tool to debug instead, check this out*

No comments:

Post a Comment