今天做了下修改,效率大概提高了1000倍吧
测试图如下:
214452542是上个方法的执行时间
250169是本次方法执行时间
图如本次方法生成图效果
更改了公式为:Y=0.299*R+0.114*G+0.587B
代码:
1
/// <summary>
2
/// 快速的将彩色图像变成黑白图像-目前仅适用于jpg格式的图像
3
/// </summary>
4
/// <param name="filePath">彩色图像地址</param>
5
/// <returns>返回的黑白图像</returns>
6
public static Bitmap QuickWhiteAndBlack(string filePath)
7
{
8
9
// 从文件创建Bitmap对象
10
Bitmap bmp = new Bitmap(filePath);
11
12
// 将Bitmap锁定到系统内存中
13
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
14
// 获得BitmapData
15
System.Drawing.Imaging.BitmapData bmpData =
16
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
17
bmp.PixelFormat);
18
19
// 位图中第一个像素数据的地址。它也可以看成是位图中的第一个扫描行
20
IntPtr ptr = bmpData.Scan0;
21
22
// 将Bitmap对象的信息存放到byte数组中
23
// 假设位图中一个像素包含3byte,也就是24bit
24
int bytes = bmp.Width * bmp.Height * 3;
25
byte[] rgbValues = new byte[bytes];
26
27
//复制GRB信息到byte数组
28
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
29
30
// 根据Y=0.299*R+0.114*G+0.587B,Y为亮度
31
for (int counter = 0; counter < rgbValues.Length; counter += 3)
32
{
33
byte value = (byte)(rgbValues[counter] * 0.299 + rgbValues[counter + 2] * 0.114 + rgbValues[counter + 1] * 0.587);
34
rgbValues[counter] = value;
35
rgbValues[counter + 1] = value;
36
rgbValues[counter + 2] = value;
37
}
38
39
//将更改过的byte[]拷贝到原位图
40
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
41
42
// 解锁位图
43
bmp.UnlockBits(bmpData);
44
return bmp;
45
46
}
上篇地址:http://www.cnblogs.com/jillzhang/archive/2006/10/09/524571.html
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

特别感谢:YaoTong
ahnan
沐枫
三位兄弟在上篇文章对我的帮助!