Tutorial :c#: how to convert image field to int[]?


c#: How would you convert an image field's data to an int array? How would you write an int array to an image field?

Has to be done in code, not procedures, I don't know which database type will be used.

Edit: I am using a blob field to store a one dimensional array of instrument readings.


Assuming you mean a SQL Server Image, typically you'll get this as a byte array or possibly as a stream. (You can wrap a byte array in a MemoryStream.)

You could either use BinaryReader around a stream or BitConverter with a byte array to convert an integer at a time, or use Buffer.BlockCopy to copy the data from a byte[] into an int[].


I'm not entirely certain what you're asking, but if you want to access the internal bit data of an image, this is how you do it.

Note the following below:

I explicitly set the PixelFormat rather than using bmp.ImageFormat. This will throw an exception if the format I picked isn't compatible with the bitmap, but at least i know how many bpp I'm getting.

I'm locking the bits in ImageLockMode.ReadOnly mode, so I can't copy the bits back in to the image. If I want to modify the bits in the image, I simply use ReadWrite mode instead, and then after I'm done manipulating the bits, I copy them back in to the BitmapData object, then unlock the Bitmap.

Finally, I'm copying the data out twice -- first as a byte[] array, and second as an Int32[] array. Normally you only do it once, and normally you use a byte array. But since you specifically said int[], I included both examples.

Bitmap bmp = new Bitmap("myimage.jpg");  BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),      ImageLockMode.ReadOnly,      PixelFormat.Format32bppRgb);    // copy as bytes  int byteCount = data.Stride * data.Height;  byte[] bytes = new byte[byteCount];  System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, byteCount);    // -- OR -- copy as ints  int wordCount = byteCount / 4;  Int32[] words = new Int32[wordCount];  System.Runtime.InteropServices.Marshal.Copy(data.Scan0, words, 0, wordCount);    bmp.UnlockBits(data);  


This seems to work. I wonder how portable it is?

[TestMethod]  public void TestMethod1()  {      int[] intArray = { 4, 8, 15, 16, 23, 42, 108, 342, 815, 1087, 6717 };        byte[] inputBytes = new byte[intArray.GetLength(0) * 4];        Buffer.BlockCopy(intArray, 0, inputBytes, 0, intArray.GetLength(0) * 4);        int[] outputInts = new int[intArray.GetLength(0)];        Buffer.BlockCopy(inputBytes, 0, outputInts, 0, intArray.GetLength(0) * 4);        Assert.IsTrue(Enumerable.SequenceEqual(intArray, outputInts));    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »