开发者

How to convert integer array into memory stream?

开发者 https://www.devze.com 2023-03-29 05:49 出处:网络
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

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 Me开发者_StackOverflowmoryStream. The problem is that the MemoryStream constructor only takes byte arrays. So What should I do?

I am programming in c#


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.


You could use the System.Buffer.BlockCopy method to copy your two dimensional image array into a flattened array. Then use the MemoryStream class to create an image:

  int[,] imgArray = new int[320, 200];      
  int[] flattenedArray = new int[320 * 200];

  Buffer.BlockCopy(imgArray, 0, flattenedArray, 0, 320 * 200 * sizeof(int));     
  MemoryStream ms = new MemoryStream(flattenedArray);

BEGIN EDIT

Sorry, I did not read your question carefully enough. Anders is right. You can't create a bitmap from a stream that does not contain information like Width, Height. You could convert your int array into a IntPtr using the GCHandle class. Then, instantiated a bitmap class with the IntPtr:

GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
IntPtr pointer =   handle.AddrOfPinnedObject();
var myBmp = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb,  pointer);

I omitted error handling.

END EDIT

Hope, this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消