Search code examples
c#silverlightmemorystreambitmapimagewriteablebitmap

JPG corrupted on upload in silverlight


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

Solution

  • 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();
        }                
    }