在图像为16bppGrayscale时从位图获取彩色图像

时间:2009-04-28 12:48:16

标签: c# bitmap imaging

问题1。 My own Related problem

我在这里问了下一个问题

现在问题2是。

当我尝试从原始像素数据打开16位(Monocrome)图像时 然后我得到错误。 因为我在创建Bitmap时使用PixelFormat.Format16bppGrayscale

Bitmap bmp = new Bitmap(Img_Width, Img_Height,PixelFormat.Format16bppGrayscale);

所以谷歌搜索并发现不支持Format16bppGrayscale所以我修改了我的代码,如下所示。

 PixelFormat format = PixelFormat.Format16bppRgb565;
 Bitmap bmp = new Bitmap(Img_Width, Img_Height, format);
 Rectangle rect = new Rectangle(0, 0, Img_Width, Img_Height);
 BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
 Marshal.Copy(rawPixel, 0, bmpData.Scan0, rawPixel.Length);
 bmp.UnlockBits(bmpData);

令人惊讶的是,我现在正在获取图像,因为我更改了pixelFormat。 但问题是我的monocrome(灰度)图像看起来有各种颜色。

我怎样才能获得原始外观。我尝试了几种灰度方法但没有成功 请给我一些不安全的代码。 谢谢,

2 个答案:

答案 0 :(得分:2)

BobPowell's GDI+ FAQ has a bit about greyscale。 .Net中的16bpp不起作用。我必须在32bpp中完成所有工作并使用外部工具进行转换。幸运的是(?)我大部分时间都会坚持使用TIFF图像。此外,this thread可能有所帮助。

答案 1 :(得分:-1)

您需要将托盘更改为灰度调色板。 8bpp Indexed的默认托盘为256色。您可以这样更改:

ColorPalette pal = myBitmap.Palette;

for (int i = 0; i < pal.Entries.Length; i++)
    pal.Entries[i] = Color.FromArgb(i, i, i);

myBitmap.Palette = pal;