扫描图像,找到图像明度的最大最小值,将max映射为255或250等较大值,min映射到0或5等较小值,重新计算各点的明度。
1 public static bool Contrast(Bitmap b, int Lavel)
2 {
3 if (Lavel < -100) return false;
4 if (Lavel > 255) return false;
5
6 BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),
7 ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
8
9 double pixel = 0, contrast = (100.0 + Lavel) / 100.0;
10 contrast *= contrast;
11
12 int stride = bmData.Stride;
13 System.IntPtr Scan0 = bmData.Scan0;
14
15 unsafe
16 {
17 byte *p = (byte *)(void *)Scan0;
18 int red, green, blue;
19 int nOffset = stride - b.Width*3;
20
21 for(int y = 0; y < b.Height; ++y)
22 {
23 for(int x = 0; x < b.Width; ++x )
24 {
25 blue = p[0];
26 green = p[1];
27 red = p[2];
28
29 pixel = blue / 255.0;
30 pixel -= 0.5;
31 pixel *= contrast;
32 pixel += 0.5;
33 pixel *= 255;
34 if (pixel < 0) pixel = 0;
35 if (pixel > 255) pixel = 255;
36 p[0] = (byte) pixel;
37
38 pixel = green / 255.0;
39 pixel -= 0.5;
40 pixel *= contrast;
41 pixel += 0.5;
42 pixel *= 255;
43 if (pixel < 0) pixel = 0;
44 if (pixel > 255) pixel = 255;
45 p[1] = (byte) pixel;
46
47 pixel = red / 255.0;
48 pixel -= 0.5;
49 pixel *= contrast;
50 pixel += 0.5;
51 pixel *= 255;
52 if (pixel < 0) pixel = 0;
53 if (pixel > 255) pixel = 255;
54 p[2] = (byte) pixel;
55
56 p += 3;
57 }
58 p += nOffset;
59 }
60 }
61 b.UnlockBits(bmData);
62 return true;
63 }
2 {
3 if (Lavel < -100) return false;
4 if (Lavel > 255) return false;
5
6 BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height),
7 ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
8
9 double pixel = 0, contrast = (100.0 + Lavel) / 100.0;
10 contrast *= contrast;
11
12 int stride = bmData.Stride;
13 System.IntPtr Scan0 = bmData.Scan0;
14
15 unsafe
16 {
17 byte *p = (byte *)(void *)Scan0;
18 int red, green, blue;
19 int nOffset = stride - b.Width*3;
20
21 for(int y = 0; y < b.Height; ++y)
22 {
23 for(int x = 0; x < b.Width; ++x )
24 {
25 blue = p[0];
26 green = p[1];
27 red = p[2];
28
29 pixel = blue / 255.0;
30 pixel -= 0.5;
31 pixel *= contrast;
32 pixel += 0.5;
33 pixel *= 255;
34 if (pixel < 0) pixel = 0;
35 if (pixel > 255) pixel = 255;
36 p[0] = (byte) pixel;
37
38 pixel = green / 255.0;
39 pixel -= 0.5;
40 pixel *= contrast;
41 pixel += 0.5;
42 pixel *= 255;
43 if (pixel < 0) pixel = 0;
44 if (pixel > 255) pixel = 255;
45 p[1] = (byte) pixel;
46
47 pixel = red / 255.0;
48 pixel -= 0.5;
49 pixel *= contrast;
50 pixel += 0.5;
51 pixel *= 255;
52 if (pixel < 0) pixel = 0;
53 if (pixel > 255) pixel = 255;
54 p[2] = (byte) pixel;
55
56 p += 3;
57 }
58 p += nOffset;
59 }
60 }
61 b.UnlockBits(bmData);
62 return true;
63 }