How to convert jpeg to array in bitmap

I have a live application in C # /. net, which currently accepts raw image data in bayer format from a set of built-in cameras and converts them to jpeg images. To save transfer time, I modified the built-in devices to encode images as jpeg before transferring. I am an experienced embedded programmer, but complete C # /. NET noob. I managed to modify the application to save arrays to a file named jpeg using this fragment: (offset 5 means skip header data in the transfer frame)

FileStream stream = File.Create(fileName); BinaryWriter writer = new BinaryWriter(stream); writer.Write(multiBuff.msgData, 5, multiBuff.dataSize - 5); writer.Close(); 

The files open perfectly, but now I want to process the data as bitmap images without the need to save and load from the file. I tried the following in a data array:

 MemoryStream stream = new MemoryStream(data); BinaryReader reader = new BinaryReader(stream); byte[] headerData = reader.ReadBytes(5); Bitmap bmpImage = new Bitmap(stream); 

But this leads to the fact that the parameter is not a valid exception. As a newbie, I'm a bit overloaded with all the classes and methods for images, and it seems that what I am doing should be common, but I cannot find examples in ordinary places. Any ideas?

+4
source share
3 answers

I think you are looking for Bitmap.FromStream() :

 Bitmap bmpImage = (Bitmap)Bitmap.FromStream(stream); 

In fact, using new Bitmap(stream) should also work - this means that the data in the stream is not a valid image - are you sure jpg is valid? You can save it to disk and open it, i.e. In Paint for testing?

+2
source

You are using the Image class.

 Image image; using (MemoryStream stream = new MemoryStream(data)) { image = Image.FromStream(stream); } 
+1
source

FYI this did not work, because reader.ReadBytes (5) returns the first 5 bytes of the stream, not bytes after position 5

0
source

Source: https://habr.com/ru/post/1341882/


All Articles