Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer array into memory stream?

I have a two dimensional array of integers. Each item in the array is a pixel value of an image that is captured from a camera. My intention is to save the image as a jpg or bitmap. I am attempting to use the Image.FromStream() method to create the image and then I can use Image.Save() to save the image in the desired format. Image.FromStream() takes a stream object as its parameter so I need to convert the integer array to a MemoryStream. The problem is that the MemoryStream constructor only takes byte arrays. So What should I do?

I am programming in c#

like image 857
PICyourBrain Avatar asked Jan 21 '26 17:01

PICyourBrain


1 Answers

You can write the array element-by-element to the memorystream:

using(BinaryWriter writer = new BinaryWriter(memoryStream)) 
{
    for(int i=0; i<arr.Length; i++) 
    {
       for(int j=0; j<arr[i].Length; j++) 
       {
          writer.Write(arr[i][j]);
       }
    }
} 

I don't think however that an image can be created from a stream containing integers, instead you probably need to create an empty Bitmap of the same Width x Height as your array, then loop (like in the code snippet above) and set pixels according to your values. Once you have set all the pixels to your bitmap, you can save it as Jpeg for example.

like image 103
Anders Forsgren Avatar answered Jan 23 '26 07:01

Anders Forsgren