Question

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();
    }                
}
Was it helpful?

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();
    }                
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top