How to manage pixel level images in C #

How to manage pixel level images in C #?

I need to be able to read / modify each of the RGB values โ€‹โ€‹of a bitmap image separately.

Sample code will be appreciated.

+42
c # image-processing image-manipulation
Oct 10 '08 at 7:15
source share
4 answers

If you need speed, LockBits . See here for a good guide to play Bob Powell . If you just want to edit a few, then GetPixel / SetPixel should do what you want.

+47
Oct 10 '08 at 7:19
source share

Code example (I use this for a simple merge and compare function. It takes two images and creates a third grayscale image showing the differences between the two images as a grayscale level. The darker, the greater the difference.):

public static Bitmap Diff(Bitmap src1, Bitmap src2, int x1, int y1, int x2, int y2, int width, int height) { Bitmap diffBM = new Bitmap(width, height, PixelFormat.Format24bppRgb); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //Get Both Colours at the pixel point Color col1 = src1.GetPixel(x1 + x, y1 + y); Color col2 = src2.GetPixel(x2 + x, y2 + y); // Get the difference RGB int r = 0, g = 0, b = 0; r = Math.Abs(col1.R - col2.R); g = Math.Abs(col1.G - col2.G); b = Math.Abs(col1.B - col2.B); // Invert the difference average int dif = 255 - ((r+g+b) / 3); // Create new grayscale RGB colour Color newcol = Color.FromArgb(dif, dif, dif); diffBM.SetPixel(x, y, newcol); } } return diffBM; } 

Mark post marks LockBits and uses this to modify the image directly in memory. I would suggest looking at this, not what I posted if performance is a problem. Thanks Marc!

+14
Oct 10 '08 at 7:31
source share

System.Drawing.Bitmap has a public method GetPixel (int x, int y) that returns the structure of System.Drawing.Color. This structure has byte elements R, G, B, and A that you can change directly, and then call SetPixel (color) on your bitmap again.
Unfortunately, this will be relatively slow, but this is easiest to do in C #. If you work a lot with individual pixels and find that there is no performance, you need something faster, you can use LockBits ... This is much more complicated, because you need to understand the structure of bits for this depth and color type, and work with a raster step and what not ... so if you find it necessary, make sure you find a good tutorial! There are several websites on the Internet that Googling โ€œC # LockBitsโ€ will bring you half a dozen worth reading.

+4
Oct 10 '08 at 7:27
source share

If performance is critical, another alternative to LockBits is DirectX.

See the previous question on stack overflow for rendering graphics in C # for more details.

Like Lockbits, you will need to use an insecure key for the keyword / compiler, but you will gain access to the high-level pixel level.

You also get better DirectX rendering performance compared to the regular Bitmap and PictureBox classes.

+2
Oct 10 '08 at 8:33
source share



All Articles