Monday, September 3, 2012

Simple Image Processing - Grayscale (C#)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * Created by SharpDevelop.
 * User: wai
 * Date: 2/9/2012
 * Time: 21:09
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.                                                       /
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

namespace PictureBox_Test
{
 /// <summary>
 /// Description of MainForm.
 /// </summary>
 public partial class MainForm : Form
 {
  PictureBox imageControl;
  
  public MainForm()
  {
   //
   // The InitializeComponent() call is required for Windows Forms designer support.
   //
   InitializeComponent();
   
   this.Size = new Size(400,300);
   
   imageControl = new PictureBox();
   imageControl.ImageLocation = "http://blog-imgs-31-origin.fc2.com/h/a/n/hanmans/pachinkotokyo18.jpg";
   imageControl.InitialImage = null;
   imageControl.Width = 400;
   imageControl.Height = 300;
   this.Controls.Add(imageControl);
   
   imageControl.LoadCompleted += PictureBox1_LoadCompleted;
  }
  private void PictureBox1_LoadCompleted(Object sender, AsyncCompletedEventArgs e) 
  {
   Bitmap image = new Bitmap(imageControl.Image);
   imageControl.Image = SetGrayscale(image);
  } 
  public Bitmap SetGrayscale(Bitmap image)
  {
   Bitmap bmap = image;
   Color c;
   for (int i = 0; i < bmap.Width; i++)
   {
    for (int j = 0; j < bmap.Height; j++)
    {
     c = bmap.GetPixel(i, j);
     byte gray = (byte)(.299 * c.R + .587 * c.G + .114 * c.B);

     bmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray));
    }
   }
   return bmap;
  }  
 }
}



No comments:

Post a Comment