我正在编写一个应用程序,假设它可以在灰度图像上运行。我在转换输入图像到8位灰度级图像时遇到了麻烦。我编写的方法是将输入图像转换为8位,但它的输出远不像灰度图像。
private Bitmap ConvertToGrayScale(Bitmap bitmap)
{
Int32 bytesPerPixel = Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
if (bytesPerPixel == 1)
return bitmap;
Bitmap grayscaleBitmap = new Bitmap(bitmap.Width, bitmap.Height,
PixelFormat.Format8bppIndexed);
Byte[] pixelData = GetPixelData(bitmap);
Byte[] grayScalePixelData = new byte[grayscaleBitmap.Width * grayscaleBitmap.Height];
for (int i = 0; i < grayScalePixelData.Length; i++)
{
var pixelValue = (Byte)
(pixelData[i * bytesPerPixel] * 0.3 + pixelData[i * bytesPerPixel + 1] * 0.59 +
pixelData[i * bytesPerPixel + 2] * 0.11);
grayScalePixelData[i] = pixelValue;
}
Rectangle rectangle = new Rectangle(0, 0, grayscaleBitmap.Width, grayscaleBitmap.Height);
BitmapData grayscaleBitmapData = grayscaleBitmap.LockBits(rectangle, ImageLockMode.WriteOnly,
grayscaleBitmap.PixelFormat);
IntPtr pointer = grayscaleBitmapData.Scan0;
Marshal.Copy(grayScalePixelData, 0, pointer, grayScalePixelData.Length);
grayscaleBitmap.UnlockBits(grayscaleBitmapData);
grayscaleBitmap.Save(@"D:\gray.jpg");
return grayscaleBitmap;
}
有谁可以指出我做错了什么?