C # WinForm color images into gray images, gray, grayscale pictures, fast, Safe,unsafe

Source: Internet
Author: User

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" >  
    1. Public TPHC ()
    2. {
    3. InitializeComponent ();
    4. this.pictureBox1.ImageLocation = "f:\\ black hair. jpg";
    5. }



button click event

C # code
  1. Private void button3_click (object sender, EventArgs e)
  2. {
  3. int Height = this.pictureBox1.Image.Height;
  4. int Width = this.pictureBox1.Image.Width;
  5. Bitmap Bitmap = new Bitmap (Width, Height);
  6. Bitmap Mybitmap = (Bitmap)this.pictureBox1.Image;
  7. Color Pixel;
  8. For (int x = 0; × < Width; x + +)
  9. For (int y = 0; y < Height; y++)
  10. {
  11. Pixel = Mybitmap.getpixel (x, y);
  12. int R, G, B, Result = 0;
  13. r = Pixel. R
  14. g = pixel. G
  15. b = pixel. B
  16. //Instance program produces black and white images with weighted average value method
  17. int iType = 2;
  18. switch (iType)
  19. {
  20. Case 0://Averaging method
  21. Result = ((r + G + B)/3);
  22. Break ;
  23. Case 1://Max value method
  24. Result = r > G? R:g;
  25. result = result > b? Result:b;
  26. Break ;
  27. Case 2://Weighted average value method
  28. Result = ((int) (0.7 * R) + (int) (0.2 * g) + (int) (0.1 * b));
  29. Break ;
  30. }
  31. Bitmap. SetPixel (x, Y, Color.FromArgb (result, result, result));
  32. }
  33. this.pictureBox1.Image = bitmap;
  34. }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.