简体   繁体   English

将像素颜色数组转换为位图的字节数组

[英]Convert Pixel Color Array to Byte Array For BitMap

I am trying to create a BitMap from a string array of pixel color values. 我正在尝试从像素颜色值的字符串数组创建BitMap The array contains 76800 elements (320 x 240) which have the pixels in decimal format (eg "11452343"). 该数组包含76800个元素(320 x 240),这些元素的像素为十进制格式(例如“ 11452343”)。

I am trying to use this function to create my BitMap 我正在尝试使用此功能来创建我的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. 我的问题发生在for循环内, for这里我尝试将十进制值转换为字节值以添加到rgbValues数组中。 How can I convert that decimal color to a byte value to add to the array? 如何将十进制颜色转换为字节值以添加到数组中?

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.. 我看到您正在构建灰度调色板,但是ARGB值不会指向该调色板。

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. 假设每个像素都有一个十进制数,我认为首先创建具有默认ARGB颜色深度的位图会更容易。

After you have painted its pixels you could change its format to Format8bppIndexed. 绘制其像素后,可以将其格式更改为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: 编辑:如果您真的想自己创建映射,则可以使用此行从十进制ARGB值decVal创建灰度8位值:

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.. 将像素设置为这些字节值应该会在您的灰度调色板中创建一个有效的映射,但是我自己还没有尝试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM