0

I got this code to convert WriteableBitmap to byte array in my previous question Converting WriteableBitmap to Byte array - Windows phone 8.1 - Silverlight

public static byte[] ConvertToByteArray(WriteableBitmap writeableBitmap)
{
  using (var ms = new MemoryStream())
  {
    writeableBitmap.SaveJpeg(ms, 
         writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
    return ms.ToArray();
  }
}

This code works but it returns arrays of different lengths every time. Is it possible to get the array of same size each time? The writeableBitmaps that it gets as parameter are always of same size.

Community
  • 1
  • 1
Saira
  • 107
  • 1
  • 12
  • 1
    It is a JPEG hence the size will depend on the compressability of the picture. AFAIK there is no easy way to always get the same size. – thumbmunkeys Mar 30 '15 at 18:24

1 Answers1

1

Jpeg is compressed image format so unless your input has identical content all the time you'll get different length in byte (even for same size of an image).

Your options:

  • update code to deal with variable size of image bytes
  • use non-compressed format (will dramatically increase size of the data)
  • pad data with 0 at the end based on max expected size of the array (you'll probably have to block some images as otherwise the size will have to be comparable to size of uncompressed image)
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I will go with the last option, adding 0 but can you please explain what do you mean by "update code to deal with variable size of image bytes"? by this you mean solve my problem without making them of same size ? – Saira Mar 30 '15 at 19:09
  • @Saira - yes, you should really expect all images to have different size in bytes - I assume there some code that calls the function and this code need to be changed to accept arbitrary array size... Note that last option is really for cases you can't use first one - uncompressed/uncompromisable images require a lot of space and you'll have to pick very long array size to accommodate less-compressible images. – Alexei Levenkov Mar 30 '15 at 19:16
  • My project really needs this the byte array and of same size as well.. well thank You for your help :) – Saira Mar 30 '15 at 19:20