访问GrayScale图像中的像素

时间:2014-07-28 13:49:56

标签: c#

如何访问使用Format16bppGrayScale格式化的GrayScale位图中的单个像素值?当我使用GetPixel()方法时,我会在System.ArgumentException中获得System.Drawing.dll

修改

以下方法创建灰度位图bmp。如何查看其内容(像素值)?

    // This method converts a 2dim-Array of Ints to a Bitmap
    public static Bitmap convertToImage(int[,] array)
    {
        Bitmap bmp;
        unsafe
        {
            fixed (int* intPtr = &array[0, 0])
            {
                bmp = new Bitmap(5, 7, 4, PixelFormat.Format16bppGrayScale, new IntPtr(intPtr));
            }
        }

        BitmapData bmpData = bmp.LockBits(new Rectangle(new Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
        IntPtr bmpPtr = bmpData.Scan0;

        // Here, I would like to see the pixel values of "bmp", which should be similar to the values in "array"

        return bmp;
    }

1 个答案:

答案 0 :(得分:0)

您可以使用位图的LockBits method锁定位并将IntPtr检索到包含像素信息的内存指针。从那里,您可以使用索引来获取您感兴趣的字节。您可以在MSDN上查看示例以获取更多信息。

<强>更新

从您的示例中获取,然后用以下代码替换您的代码:

// This method converts a 2dim-Array of Ints to a Bitmap
public static Bitmap convertToImage(int[,] array)
{
    Bitmap bmp;
    unsafe
    {
        fixed (int* intPtr = &array[0, 0])
        {
            bmp = new Bitmap(5, 7, 4, PixelFormat.Format16bppGrayScale, new IntPtr(intPtr));
        }
    }

    BitmapData bmpData = bmp.LockBits(new Rectangle(new Point(), bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
    IntPtr bmpPtr = bmpData.Scan0;

    byte[] dataAsBytes = new byte[bmpData.Stride * bmpData.Height];
    System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, dataAsBytes, 0, dataAsBytes.Length);

    // Here dataAsBytes contains the pixel data of bmp

    return bmp;
}

您可以使用bmpData.Stride / bmp.Width来查找每个像素更容易导航数组所需的字节大小。

更新#2

要使用indexOfPixel查找像素的第一个字节数据,您可以执行以下操作:

byte firstByteOfPixel = indexOfPixel * bmpData.Stride / bmp.Width;
byte secondByteOfPixel = 1 + (indexOfPixel * bmpData.Stride / bmp.Width);

您可以将其与多维数组进行比较。

相关问题