1

am trying to convert a grayscale image to a byte array. I use the following code. however, the byte array generated is not of the logical size.

ImageConverter converter = new ImageConverter();
byte[] test = (byte[])converter.ConvertTo(gpuMatch.Bitmap,typeof(byte[]));

the image is a grayscale 792x410 8 bit depth. so should'nt the array size be 324720 bytes? i am getting something close to 140122 elements in the byte array.

ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(test);

if i reconvert the bytes to image, the image is intact. can someone please explain as to why is this mismatch?

thanks kannan

default locale
  • 13,035
  • 13
  • 56
  • 62
kannan
  • 11
  • 1
  • 2

3 Answers3

2

The returned byte array is not a raw representation of the image where one byte represents one pixel. Instead it depends on the image format. So you will get different results for jpeg, gif, png end so on.

I think this link will be usefull:

http://www.vcskicks.com/image-to-byte.php

(this is taken from this answer: Convert a bitmap into a byte array)

The linked page reads:

The thing to remember about ImageConverter, is that the image will be directly converted into bytes. Thus an image in bmp format and the same image in png format will NOT have the same byte array. So if you want to the compare two images for example, you would have to make sure they are first in the same format before comparing their byte arrays.

So i think you will notice that die byte array will always be roughly in size with the image-file you read in.

Community
  • 1
  • 1
Scheintod
  • 7,953
  • 9
  • 42
  • 61
  • Makes me wonder what possible use `ImageConverter` could have that's better than `Image.Save(memstream, format)`, or, heck, `File.ReadAllBytes(path)`. – Nyerguds Jan 09 '18 at 09:10
0

When a bit map is created, there is some optimization that happens. You will find that there could be a global colour palette defined in the image that is reused through out the image. This means it wont rewrite the colours byte values all over the file - resulting in less bytes being written.

Thanks, Dave

TheDaveJay
  • 753
  • 6
  • 11
0

when i use the stream method, i get the actual hex data. apparently, image converter uses image type (defaults to PNG?) during the bytes conversion process. hence the mismatch in byte array size.

thanks for your support, kannan

kannan
  • 11
  • 1
  • 2