问题
I have already used the LockBits and UnlockBits functions and takes the byte array of a Image into a 1D array. (considering only the black and white/binarized images)
Is there any way of taking it to a 2D array (of the size image height and width)? so i can wirte the array into a ".txt" file and view it?
The code i have used to take the image into 1D array is as below:
Public void function(Bitmap image){
{
byte[] arr1D;
byte[] arr2D;
BitmapData data = image.LockBits(new Rectangle(0, 0, img_w, img_h), ImageLockMode.ReadOnly, image.PixelFormat);
try
{
IntPtr ptr = data.Scan0;
int bytes = Math.Abs(data.Stride) * image.Height;
byte[] rgbValues = new byte[bytes];
arr1D = rgbValues;
Marshal.Copy(ptr, rgbValues, 0, bytes);
}
finally
{
image.UnlockBits(data);
}
}
Since the image is binary, the values of the Byte array is from only 255 and 0.
Instead of extracting the entire image to a 1D array, is there any method/code where i can extract pixel row by row to a 2D array, Where i can write it to a text file and see later on?
Programming Language : C#
example: (if the value 255 is replaced with 1)
result output: 1D array: (6px X 6px image)
0 0 1 1 0 0 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 0 0 1 1 0 0
expected output: 2D array: (6px X 6px image)
0 0 1 1 0 0
0 0 1 1 0 0
1 1 1 1 1 1
1 1 1 1 1 1
0 0 1 1 0 0
0 0 1 1 0 0
Can someone please help me with the code for it in C#?
回答1:
Here's a simple function that takes a 1d int array and the size of each row you want the data split up into and returns a 2d array.
public int[,] ConvertArray(int[] Input, int size)
{
int[,] Output = new int[(int)(Input.Length/size),size];
System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\OutFile.txt");
for (int i = 0; i < Input.Length; i += size)
{
for (int j = 0; j < size; j++)
{
Output[(int)(i / size), j] = Input[i + j];
sw.Write(Input[i + j]);
}
sw.WriteLine("");
}
sw.Close();
return Output;
}
I didn't add any validation to make sure the input array is exactly divisible by the size, if necessary you'll need to add that.
I did add code to write the data to a file.
来源:https://stackoverflow.com/questions/17387509/how-to-convert-1d-byte-array-to-2d-byte-array-which-holds-a-bitmap