Setting pixel color of BMP/JPG file
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);
}
}
Every time I get the following exception:
Unhandled Exception: System.InvalidOperationException: SetPixel is not supported for images with indexed pixel formats.
The开发者_StackOverflow社区 exception is thrown both for bmp
and jpg
files.
You have to convert the image from indexed to non indexed. Try this code to convert it:
public Bitmap CreateNonIndexedImage(Image src)
{
Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics gfx = Graphics.FromImage(newBmp)) {
gfx.DrawImage(src, 0, 0);
}
return newBmp;
}
try the following
Bitmap myBitmap = new Bitmap(@"c:\file.bmp");
MessageBox.Show(myBitmap.PixelFormat.ToString());
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;
}
The same conversion can be done using "clone" method.
Bitmap IndexedImage = new Bitmap(imageFile);
Bitmap bitmap = IndexedImage.Clone(new Rectangle(0, 0, IndexedImage.Width, IndexedImage.Height), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
精彩评论