Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 2D array to bitmap image. C#

Tags:

arrays

c#

bitmap

I'm working on a project to show a 2D world generation process in steps using bitmap images. Array data is stored in this way:

Main.tile[i, j].type = x;

With x being an integer value >= 0.

Basically i and j are changed every time the program loops using for-loops, and the following statement is run after certain conditions are met during the loop process at the end of the loop. So, a possible sequence could be:

Main.tile[4, 67].type = 1;
Main.tile[4, 68].type = 1;
Main.tile[4, 69].type = 0;

And so on.

I tried several methods of directly modifying the bitmap image once the array was changed/updated (using Bitmap.SetPixel), but this seemed way to slow to be useful for a 21k,8k pixel resoltion bitmap.

I'm looking for a way to digest the whole array at the end of the whole looping process (not after each individual loop, but between steps), and put colored points (depending on the value of the array) accordingly to i, j (as if it were a coordinate system).

Are there any faster alternatives to SetPixel, or are there easier ways to save an array to a bitmap/image file?

like image 217
user2399399 Avatar asked Aug 24 '26 22:08

user2399399


1 Answers

Change your array to one dimension array and apply all operation on the one dimension array and ONLY if you want to display the image change it back to 2 dimension.

How to change whole array from 2D to 1D:

byte[,] imageData = new byte[1, 2]
{ 
    {  1,  2 }
    {  3,  4 }
 };

var mergedData = new byte[ImageData.Length];

// Output { 1, 2, 3, 4 }
Buffer.BlockCopy(imageData, 0, mergedData, 0, imageData.Length);

From 2D to 1D:

// depending on whether you read from left to right or top to bottom.
index = x + (y * width)
index = y + (x * height)

From 1D to 2D:

x = index % width
y = index / width or

x = index / height
y = index % height

I hope this will solve your problem!

like image 62
Bassam Alugili Avatar answered Aug 26 '26 13:08

Bassam Alugili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!