I want to convert a Bitmap image into a 2D array of integers and vice versa.
I have written the given code.
And, this is my driver program:
private void forwardFftButton_Click(object sender, EventArgs e)
{
Bitmap grayscale = (Bitmap) GrayscaleUtils.ColorToGrayscale(inputImagePictureBox.Image);
grayscaleImagePictureBox.Image = grayscale;
int[,] array2D = ImageDataConverter.BitmapToArray2D(grayscale);
Bitmap grayScaleAgain = ImageDataConverter.Array2DToBitmap(array2D);
processedImagePictureBox.Image = grayScaleAgain;
}
This is the result:[
^]
The conversion isn't working.
What is the bug in my code?
What I have tried:
using System;
using System.Drawing;
using System.Drawing.Imaging;
public partial class ImageDataConverter
{
public static int[, ] BitmapToArray2D(Bitmap image)
{
int[, ] array2D = null;
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
array2D = new int[image.Width, image.Height];
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
int paddingOffset = bitmapData.Stride - (bitmapData.Width * 1);
unsafe
{
byte *memoryAddress = (byte *)bitmapData.Scan0;
for (int i = 0; i < bitmapData.Width; i++)
{
for (int j = 0; j < bitmapData.Height; j++)
{
byte tempByte = memoryAddress[0];
array2D[i, j] = (int)tempByte;
int tempArrayElement = array2D[i, j];
memoryAddress += 1;
}
memoryAddress += paddingOffset;
}
}
image.UnlockBits(bitmapData);
}
else
{
throw new Exception("8 bit/pixel indexed image required.");
}
return array2D;
}
public static Bitmap Array2DToBitmap(int[, ] image)
{
Bitmap output = new Bitmap(image.GetLength(0), image.GetLength(1));
BitmapData bitmapData = output.LockBits(new Rectangle(0, 0, image.GetLength(0), image.GetLength(1)), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
int paddingOffset = bitmapData.Stride - (bitmapData.Width * 1);
unsafe
{
byte *memoryAddress = (byte *)bitmapData.Scan0;
for (int i = 0; i < bitmapData.Height; i++)
{
for (int j = 0; j < bitmapData.Width; j++)
{
int tempInt = image[j, i];
memoryAddress[0] = (byte)tempInt;
byte tempByte = memoryAddress[0];
memoryAddress += 1;
}
memoryAddress += paddingOffset;
}
}
output.UnlockBits(bitmapData);
return output;
}
}