C#Bitmap SetPixel

时间:2015-10-14 16:42:24

标签: c# bitmap

我正在尝试为我的课程做一些作业,而我在Bitmap对象上遇到了SetPixel方法的问题。

            // Retrieve the image.
            image = new Bitmap(FileLocation);
            SobelImage = image;

            int x, y;

            // Loop through the images pixels to reset color.
            for (x = 0; x < image.Width; x++)
            {
                for (y = 0; y < image.Height; y++)
                {

                    Console.WriteLine(String.Format("At {0} : {1}, Brightness : {2}", x, y, image.GetPixel(x, y).GetBrightness()));


                    Pixel pixel = new Pixel(image.GetPixel(x, y).GetBrightness());

                    SobelImage.SetPixel(x, y, Color.FromArgb(image.GetPixel(x, y).R, 0, 0)); 
                 }
             }

请帮助,这是例外: System.Drawing.dll中出现未处理的“System.InvalidOperationException”类型异常

其他信息:带有索引像素格式的图片不支持SetPixel。

2 个答案:

答案 0 :(得分:1)

正如错误消息所示,此类图片不支持SetPixel方法。

您的图像格式带有索引颜色,例如GIF或8位PNG,其中每个像素的颜色是调色板的索引。您无法更改像素的颜色,因为颜色实际上并未存储在像素中。

要使用SetPixel方法,您可以创建一个新的空位图,该位图将采用32位argb格式,并在其上绘制图像:

Bitmap newImage = new Bitmap(image.Width, image.Height);
using (Graphics graphics = Graphics.FromImage(newImage)) {
  graphics.DrawImage(image, 0, 0);
}

新图片将支持SetPixel。请注意,保存时图像格式会有所不同。

答案 1 :(得分:0)

您无法在索引位图中设置单个像素,因为存储数据的方式。对于索引位图,RGB值来自索引的表,但它是单向操作 - 您不能仅从RGB值获取索引,因为在PutPixel操作时表无法获得合适的值。可以从RGB位图中的所有RGB值创建新表,同时处理整个图片,这是非常昂贵的操作。

您需要以RGB格式创建新的位图,并将像素放在那里。

Bitmap newImage = new Bitmap(sourceImage.Width, sourceImagr.Height);

作为旁注,您应该在using构造中使用Bitmap对象。