Home » C# ProgrammingRSS

How to set pixel into bitmap with Pixel format of Format8bppIndexed ?

I define new bitmap in my code 

Bitmap image = new Bitmap( width, height, PixelFormat.Format8bppIndexed);

==> that mean that this bitmap is gray scale color. 

Now, i want to define what color will be at place (i, j) so i usually use ( on 24 color bit ) the method 'SetPixel( i, j, Color.FromRGB( ... ) )'

But in this case that the bitmap is on gray scale i cant do it because i have only one value of the color ... and the application crash all the time when i try to 
call Color.FromRGB(theOneColorIhave)

Someone know other way to do set the pixel values - some way that can be use with 8 bit format ? 

Thanks
 

3 Answers Found

 

Answer 1

For changing pixels in an image with an indexed format, you need to change the bytes constituting the image. You cannot use SetPixel.

// For comparison
Color colorBefore = image.GetPixel(5, 5);

BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);

// Copy the bytes from the image into a byte arraybyte[] bytes = newbyte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

bytes[5 * data.Stride + 5] = 1; // Set the pixel at (5, 5) to the color #1// Copy the bytes from the byte array into the image
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);

image.UnlockBits(data);

// You can check the pixel has been changed
Color colorAfter = image.GetPixel(5, 5);

Console.WriteLine("Pixel changed from {0} to {1}.", colorBefore, colorAfter);
 

Answer 2

I define new bitmap in my code 

Bitmap image = new Bitmap( width, height, PixelFormat.Format8bppIndexed);

==> that mean that this bitmap is gray scale color. 
How did you make the gray scale palette?  The default palette for Format8bppIndexed isn't gray scale.
 

Answer 3

Everything you need to know about indexed GDI+ images in a nutshell:

    private void button1_Click(object sender, EventArgs e)
    {
      
int width = 256;
      
int height = 256;
      
int stride = 4 * ((width * 8 + 31) / 32);
      
byte[,] b = new byte[height, stride];
      
GCHandle gch = GCHandle.Alloc(b, GCHandleType.Pinned);
      
Bitmap bmp = new Bitmap(width,
                              height,
                              stride,
                              
PixelFormat.Format8bppIndexed,
                              gch.AddrOfPinnedObject());
      
ColorPalette pal = bmp.Palette;
      
for (int i = 0; i < 256; i++)
        pal.Entries[i] = 
Color.FromArgb(255, i, i, i);
      bmp.Palette = pal;
      
for (int y = 0; y < height; y++)
        
for (int x = 0; x < width; x++)
          b[y, x] = (
byte)y;
      gch.Free();
    }

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter