设置BMP / JPG文件的像素颜色 [英] Setting pixel color of BMP/JPG file

查看:147
本文介绍了设置BMP / JPG文件的像素颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置图像的给定像素的颜色。
以下是代码段

I'm trying to set a color of given pixel of the image. Here is the code snippet

        Bitmap myBitmap = new Bitmap(@"c:\file.bmp");

        for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
        {
            for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
            {
                myBitmap.SetPixel(Xcount, Ycount, Color.Black);
            }
        }

每次我收到以下异常:


未处理的异常:System.InvalidOperationException:对于具有索引像素格式的图像,SetPixel不支持

Unhandled Exception: System.InvalidOperationException: SetPixel is not supported for images with indexed pixel formats.

bmp jpg 文件都抛出异常。

推荐答案

尝试以下

Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());

如果你得到Format8bppIndexed,那么Bitmap的每个像素的颜色都被一个索引替换成256色的表。
因此每个像素仅由一个字节表示。
你可以获得一系列颜色:

If you get "Format8bppIndexed" then the color of each pixel of the Bitmap is replaced by an index into a table of 256 Colors. and therefor each pixel is represented by only one byte. you can get an array of colors:

if (myBitmap.PixelFormat == PixelFormat.Format8bppIndexed) {
    Color[] colorpal = myBitmap.Palette.Entries;
}

这篇关于设置BMP / JPG文件的像素颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆