Convert color images to gray images, directly using the. NET interface to traverse each pixel point conversion is very inefficient, 800K picture 650,000 pixels My computer takes 5 minutes, and with unsafe, the speed increases thousands of times times, the same picture only uses 0. seconds
A common code for traversing pixel-point conversions
constructor function
C # code < param name= "allowscriptaccess" value= "always" >
- Public TPHC ()
- {
- InitializeComponent ();
- this.pictureBox1.ImageLocation = "f:\\ black hair. jpg";
- }
button click event
C # code
- Private void button3_click (object sender, EventArgs e)
- {
- int Height = this.pictureBox1.Image.Height;
- int Width = this.pictureBox1.Image.Width;
- Bitmap Bitmap = new Bitmap (Width, Height);
- Bitmap Mybitmap = (Bitmap)this.pictureBox1.Image;
- Color Pixel;
- For (int x = 0; × < Width; x + +)
- For (int y = 0; y < Height; y++)
- {
- Pixel = Mybitmap.getpixel (x, y);
- int R, G, B, Result = 0;
- r = Pixel. R
- g = pixel. G
- b = pixel. B
- //Instance program produces black and white images with weighted average value method
- int iType = 2;
- switch (iType)
- {
- Case 0://Averaging method
- Result = ((r + G + B)/3);
- Break ;
- Case 1://Max value method
- Result = r > G? R:g;
- result = result > b? Result:b;
- Break ;
- Case 2://Weighted average value method
- Result = ((int) (0.7 * R) + (int) (0.2 * g) + (int) (0.1 * b));
- Break ;
- }
- Bitmap. SetPixel (x, Y, Color.FromArgb (result, result, result));
- }
- this.pictureBox1.Image = bitmap;
- }