首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GrayScale图像中的存取象素

GrayScale图像中的存取象素
EN

Stack Overflow用户
提问于 2014-07-28 13:49:55
回答 1查看 2.2K关注 0票数 0

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

编辑:

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

代码语言:javascript
复制
    // 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;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-28 13:53:33

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

更新

从您的示例中,将代码替换为以下代码:

代码语言:javascript
复制
// 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查找像素的第一个字节数据,可以这样做:

代码语言:javascript
复制
byte firstByteOfPixel = indexOfPixel * bmpData.Stride / bmp.Width;
byte secondByteOfPixel = 1 + (indexOfPixel * bmpData.Stride / bmp.Width);

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24996771

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档