0

I am trying to create a BitMap from a string array of pixel color values. The array contains 76800 elements (320 x 240) which have the pixels in decimal format (e.g. "11452343").

I am trying to use this function to create my BitMap

var b = new Bitmap(320, 240, PixelFormat.Format8bppIndexed);
var ncp = b.Palette;
for (int i = 0; i < 256; i++)
    ncp.Entries[i] = Color.FromArgb(255, i, i, i);
b.Palette = ncp;

var BoundsRect = new Rectangle(0, 0, 320, 240);
var bmpData = b.LockBits(BoundsRect, ImageLockMode.WriteOnly, b.PixelFormat);

var ptr = bmpData.Scan0;
var bytes = bmpData.Stride * b.Height;
var rgbValues = new byte[bytes];

for (var i = 0; i < pixelArray.Length; i++)
{
    // ISSUE OCCURS HERE
    rgbValues[i] = byte.Parse(pixelArray[i]);
}

Marshal.Copy(rgbValues, 0, ptr, bytes);
b.UnlockBits(bmpData);

My issue occurs inside the for loop where I try to convert the decimal value to a byte value to add to the rgbValues array. How can I convert that decimal color to a byte value to add to the array?

10
  • 1
    what is the pixelformat of the string color and do you need the Bitmap to be in PixelFormat.Format8bppIndexed? Commented Jun 13, 2014 at 18:48
  • 1
    the pixels in decimal format (e.g. "11452343") is that rgb? or just a typo? Commented Jun 13, 2014 at 18:53
  • A byte is -128 to 127 by definition so you can't; unless you use encoding. Commented Jun 13, 2014 at 18:56
  • 1
    @Gabe: Actually, byte is 0 to 255. sbyte is -128 to 127. Commented Jun 13, 2014 at 18:58
  • Ah right, in C# bytes are implicitly unsigned Commented Jun 13, 2014 at 19:00

1 Answer 1

1

From what I hope I understand I think you are not doing this right..

I see you are building a greyscale palette but the ARGB values will not point into that palette..

Assuming that you have a decimal number for each pixel, I think it would be easier to first create a Bitmap with default ARGB color depth.

After you have painted its pixels you could change its format to Format8bppIndexed.

Creating the palette and the pixel index values will be best done by system routines.

Edit: If you really want to create the mapping yourself, you can use this line to create a greyscale 8-bit value from a decimal ARGB value decVal:

int grey = (byte)(Color.FromArgb(decVal).GetBrightness() * 255);

Setting the pixels to these byte values should create a working mapping into your greyscale palette but it I haven't tried it myself yet..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.