如何访问使用GrayScale格式的Format16bppGrayScale位图中的单个像素值?当我使用GetPixel()方法时,我在System.Drawing.dll中得到了一个System.ArgumentException。
编辑:
下面的方法创建一个灰度位图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;
}发布于 2014-07-28 13:53:33
您可以使用位图的LockBits法锁定位,并检索到包含像素信息的内存指针的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);您可以将其与多维数组进行比较。
https://stackoverflow.com/questions/24996771
复制相似问题