Notice: I've added the new category "WP7 Fast Tips" to collect fast tips I found while developing my Windows Phone Applications. You Don't expect only great tips in this category but also simple things I need fo remember or I found with some difficulties :)
Working on an application I hope to publish soon on the marketplace, I have the need to save an image from a WriteableBitmap instance into a Jpeg file. It was not an easy search but finally I found a couple of methods, added as Extension Methods to the WriteableBitmap class itself. If you need to encode a jpeg to a byte array you can use this code:
1: public byte EncodeToJpeg(WriteableBitmap wb)
3: using(MemoryStream stream = new MemoryStream())
5: // this is Extensions.SaveJpeg() method
6: wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 0, 85);
7: return stream.ToArray();
The parameters of the SaveJpeg method require a stream to write to, the size of the bitmap to generate and the quality from 0 to 100. The fourth parameter, called orientation, currently is not used and you can set it to 0 (zero).
The counterpart of the SaveJpeg methos is LoadJpeg that you can use to take a Jpeg file and load it into a WriteableBitmap instance. A very useful feature. If you need to write the Jpeg to the MediaLibrary probably the better is to pass the generated stream directly to the Save method.