0

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.

Community
  • 1
  • 1
PAPP
  • 57
  • 10
  • 3
    You probably ought to create the Bitmap in `8pp` format if that is what you want : `Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);` – TaW Jun 08 '16 at 15:29
  • @TaW Thank you for your answer. I modified line of code according to your suggestions, but unfortunately nothing has changed. – PAPP Jun 08 '16 at 17:17
  • 2
    I hope you are still adding/setting the Palette. It was empty when the Bitmap was not indexed; now it should make a difference.. Without setting it it will contain random colors afaik. – TaW Jun 08 '16 at 17:29
  • @TaW Thank you. Now everything works. I forgot about re-add the code responsible for resetting the palette. You were right. – PAPP Jun 08 '16 at 17:47

0 Answers0