0

After an image is taken with CameraCaptureTask it should be uploaded to server. The uploaded JPG on server side seems to have correct file size but is corrupted. Also imageBuffer seems to have all bytes set to 0. Any idea of what is wrong with the code below?

if (bitmapImage != null) {
    // create WriteableBitmap object from captured BitmapImage
    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);

    using (MemoryStream ms = new MemoryStream())
    {
        writeableBitmap.SaveJpeg(ms, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);

        imageBuffer = new byte[ms.Length];
        ms.Read(imageBuffer, 0, imageBuffer.Length);
        ms.Dispose();
    }                
}
Diego C Nascimento
  • 2,801
  • 1
  • 17
  • 23
  • Does `SaveJpeg` reposition the stream back to position 0 afterwards? Otherwise, wouldn't the position of the stream be *after* the saved image? – Lasse V. Karlsen Jan 10 '14 at 21:04

1 Answers1

0

The method SaveJpeg changes the stream current position. To properly preserve the contents of the stream, you need to read it from the beginning (i.e. set position to 0). Try this:

if (bitmapImage != null) {
    // create WriteableBitmap object from captured BitmapImage
    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);

    using (MemoryStream ms = new MemoryStream())
    {
        writeableBitmap.SaveJpeg(ms, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);

        ms.Position = 0;
        imageBuffer = new byte[ms.Length];
        ms.Read(imageBuffer, 0, imageBuffer.Length);
        ms.Dispose();
    }                
}
Memoizer
  • 2,231
  • 1
  • 14
  • 14
  • Please type up a textual description of what you changed so that future visitors to this question won't have to basically diff the two pieces of code to figure out why one works and the other doesn't. – Lasse V. Karlsen Jan 10 '14 at 21:36
  • 1
    It started to correctly work after I set ms.Position = 0 what repositioned stream back to 0. – user3153110 Jan 11 '14 at 10:58