将一维数组转换为灰度位图 C#

问题描述 投票:0回答:1

我有一维数组,其中包含范围 [50,600] 内的像素值。我需要创建一个位图并将图像保存为灰度。

我尝试了下面的代码,但我的图像是蓝色的,我对该图像的期望应该是灰色的。

            var bitmap = new Bitmap(xL, yL, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);
            int count = 0;
            for (y = 0; y < xL; y++)
            {
                for (x = 0; x < yL; x++)
                {
                    bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb((int) arr[count]));
                    count++;
                }
            }
            bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);

由于这些值不是 8 位,所以我没有使用 System.Drawing.Color.FromArgb(val,val,val),因为它给出了异常“值应该大于或等于 0 且小于 256”。

如果我的数组值在 [50,600] 范围内,如何创建灰度图像。

任何帮助将不胜感激。 谢谢。

c# .net bitmap
1个回答
0
投票

您需要手动进行颜色转换。既然你说值的范围是 [50...600],我假设你的数组

arr
的类型是
short[]

int value = ((arr[count] - 50) * 256) / 550;
value = Math.Clamp(value, 0, 255);
Color gray = Color.FromArgb(value, value, value);

这应该会给你你正在寻找的灰度值。

© www.soinside.com 2019 - 2024. All rights reserved.