I am trying to Binary Serialize a WriteableBitmap to a stream.
I found a way around this error, but it is very wasteful.
Here is my code:
public void FromandTo() { var uri = new Uri("Assets/test1.jpg", UriKind.Relative); var resourceInfo = Application.GetResourceStream(uri); var bmp = new BitmapImage(); bmp.SetSource(resourceInfo.Stream); var wb = new WriteableBitmap(bmp); using (var ms = new MemoryStream()) { WriteBMP(ms, wb); wb = null; wb = ReadBMP(ms); } } public void WriteBMP(Stream stream, WriteableBitmap value) { var bw = new BinaryWriter(stream); var wb = (WriteableBitmap)value; int pixelWidth = wb.PixelWidth; int pixelHeight = wb.PixelHeight; bw.Write(pixelWidth); bw.Write(pixelHeight); wb.SaveJpeg(bw.BaseStream, pixelWidth, pixelHeight, 0, 100); } public WriteableBitmap ReadBMP(Stream stream) { var br = new BinaryReader(stream); var pixelWidth = br.ReadInt32(); var pixelHeight = br.ReadInt32(); var wb = new WriteableBitmap(pixelWidth, pixelHeight); wb.LoadJpeg(br.BaseStream); return wb; }
The solution involves saving the jpeg to an intermediate stream (yes, another), and using the binarywriter to write that stream to the original stream. Also reading, you read to an intermediate stream, and then load from that stream.
Keep in mind that other things are being serialized to this stream besides the image, before and after the image. But in the same order every time.
-Francisco Aguilera University of Washington Student | Prospective Computer Science Major | Microsoft Student Partner http://students.washington.edu/falven | http://www.facebook.com/falven