简体   繁体   中英

Converting 2D array to bitmap image. C#

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM