Reputation: 329
I'm trying to write a program in c# to send a frame via ethernet.
Currently I have .jpg test images in 1920x1080 resolution and very different sizes in bytes.
I am trying to convert a .jpg image to a byte array, I looked for similar answers but when I tried them I got byte arrays including 437, 1030, 1013 bytes for each image. Considering that the images are in HD resolution, this does not make sense. How can I convert an image file to form a 1920*1080*3 (RGB) byte array? Please keep in mind that I am trying to develop a real time application that should be able to send frames at a high rate so this code cannot be slow.
Thanks in advance. Tunc
Upvotes: 0
Views: 7349
Reputation: 186668
JPG is a compressed format, that's why its size (and size of the corresponding Byte array) will be usually far less than 1920*1080*3. In order to get Byte array from JPG you can use streams:
Image myImage;
...
byte[] result;
using (MemoryStream ms = new MemoryStream()) {
myImage.Save(ms, ImageFormat.Jpeg);
result = ms.ToArray();
}
If all you want are pixels in a form of Byte array you have to convert your JPG into BMP (or other raw, uncompressed format)
Bitmap myImage;
...
byte[] rgbValues = null;
BitmapData data = myImage.LockBits(new Rectangle(0, 0, myImage.Width, myImage.Height), ImageLockMode.ReadOnly, value.PixelFormat);
try {
IntPtr ptr = data.Scan0;
int bytes = Math.Abs(data.Stride) * myImage.Height;
rgbValues = new byte[bytes];
Marshal.Copy(ptr, rgbValues, 0, bytes);
}
finally {
myImage.UnlockBits(data);
}
}
Upvotes: 0
Reputation: 3273
to read Image
bytes to byte array:
Image image = ...;
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
if (ms.Length == 0)
{
ms.Close();
throw new Exception("Bad Image File");
}
ms.Position = 0;
byte[] baImageBytes = new byte[ms.Length];
ms.Read(baImageBytes , 0, (int)ms.Length);
ms.Close();
to create image from byte array:
byte[] baImageBytes =...
Image myImage = Image.FromStream(new MemoryStream(baImageBytes ));
Upvotes: 1