I would like to ask for help. I want to create an image from array and show it in PictureBox. But image, that was supposed to be in gray scale, is displayed in strange colors. In the past, I have had such a problem, but the methods used until now have failed. Here is my code:
public static Bitmap BitmapFromArray(int[] pixelValues,int rows, int columns)
{
Bitmap bitmap = new Bitmap(rows, columns);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, rows, columns), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
byte[] pixelValuesOriginal = new byte[Math.Abs(bmpData.Stride) * bitmap.Height];
//Pobierz wartosc wszystkich punktow obrazu
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, pixelValuesOriginal, 0, pixelValues.Length);
for (int i = 0; i < pixelValues.Length; i++)
{
pixelValuesOriginal[i] = (byte)pixelValues[i];
}
//Ustaw wartosc wszystkich punktow obrazu
System.Runtime.InteropServices.Marshal.Copy(pixelValuesOriginal, 0, bmpData.Scan0, pixelValuesOriginal.Length);
bitmap.UnlockBits(bmpData);
return bitmap;
}
I tried the method that I found here: Editing 8bpp indexed Bitmaps
ColorPalette pal = bitmap.Palette;
for (int i = 0; i <= 255; i++)
{
pal.Entries[i] = Color.FromArgb(i, i, i);
}
bitmap.Palette = pal;
But this time it did not work because bitmap.Palette.Entries is an array with 0 elements.
I also tried to change the PixelFormat for PixelFormat.Format24bppRgb and use such a trick:
for (int i = 0; i < pixelValues.Length; i++)
{
for (int j = 0; j < 3; j++)
{
pixelValuesOriginal[i + j] = (byte)pixelValues[i];
}
}
But then I have three gray scaled pictures side by side.
I will be grateful for hints on what to do with this problem.