转载自:http://www.cnblogs.com/xiashengwang/p/4225848.html

2015-01-15 11:38 by xiashengwang, 585 阅读, 0 评论, 收藏编辑

用Bitmap.GetPixel和Bitmap.SetPixel访问像素点实在是太慢了,必须要用LockBits的方式访问内存才能改善,这里贴一个快速访问Bitmap每个像素点的包装类,是国外一个老外写的,感觉很好用。

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
public class LockBitmap
{
    Bitmap source = null;
    IntPtr Iptr = IntPtr.Zero;
    BitmapData bitmapData = null;
 
    public byte[] Pixels { get; set; }
    public int Depth { get; private set; }
    public int Width { get; private set; }
    public int Height { get; private set; }
 
    public LockBitmap(Bitmap source)
    {
        this.source = source;
    }
 
    /// <summary>
    /// Lock bitmap data
    /// </summary>
    public void LockBits()
    {
        try
        {
            // Get width and height of bitmap
            Width = source.Width;
            Height = source.Height;
 
            // get total locked pixels count
            int PixelCount = Width * Height;
 
            // Create rectangle to lock
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, Width, Height);
 
            // get source bitmap pixel format size
            Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat);
 
            // Check if bpp (Bits Per Pixel) is 8, 24, or 32
            if (Depth != 8 && Depth != 24 && Depth != 32)
            {
                throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
            }
 
            // Lock bitmap and return bitmap data
            bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite,
                                         source.PixelFormat);
 
            // create byte array to copy pixel values
            int step = Depth / 8;
            Pixels = new byte[PixelCount * step];
            Iptr = bitmapData.Scan0;
 
            // Copy data from pointer to array
            Marshal.Copy(Iptr, Pixels, 0, Pixels.Length);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    /// <summary>
    /// Unlock bitmap data
    /// </summary>
    public void UnlockBits()
    {
        try
        {
            // Copy data from byte array to pointer
            Marshal.Copy(Pixels, 0, Iptr, Pixels.Length);
 
            // Unlock bitmap data
            source.UnlockBits(bitmapData);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    /// <summary>
    /// Get the color of the specified pixel
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    public Color GetPixel(int x, int y)
    {
        Color clr = Color.Empty;
 
        // Get color components count
        int cCount = Depth / 8;
 
        // Get start index of the specified pixel
        int i = ((y * Width) + x) * cCount;
 
        if (i > Pixels.Length - cCount)
            throw new IndexOutOfRangeException();
 
        if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            byte a = Pixels[i + 3]; // a
            clr = Color.FromArgb(a, r, g, b);
        }
        if (Depth == 24) // For 24 bpp get Red, Green and Blue
        {
            byte b = Pixels[i];
            byte g = Pixels[i + 1];
            byte r = Pixels[i + 2];
            clr = Color.FromArgb(r, g, b);
        }
        if (Depth == 8)
        // For 8 bpp get color value (Red, Green and Blue values are the same)
        {
            byte c = Pixels[i];
            clr = Color.FromArgb(c, c, c);
        }
        return clr;
    }
 
    /// <summary>
    /// Set the color of the specified pixel
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <param name="color"></param>
    public void SetPixel(int x, int y, Color color)
    {
        // Get color components count
        int cCount = Depth / 8;
 
        // Get start index of the specified pixel
        int i = ((y * Width) + x) * cCount;
 
        if (Depth == 32) // For 32 bpp set Red, Green, Blue and Alpha
        {
            Pixels[i] = color.B;
            Pixels[i + 1] = color.G;
            Pixels[i + 2] = color.R;
            Pixels[i + 3] = color.A;
        }
        if (Depth == 24) // For 24 bpp set Red, Green and Blue
        {
            Pixels[i] = color.B;
            Pixels[i + 1] = color.G;
            Pixels[i + 2] = color.R;
        }
        if (Depth == 8)
        // For 8 bpp set color value (Red, Green and Blue values are the same)
        {
            Pixels[i] = color.B;
        }
    }
 
    public bool IsValidCoordinate(int x, int y)
    {
        return x >= 0 && x < this.Width && y > 0 && y < this.Height;
    }
}

还有一个时间测算的类,可以计算代码的时间差,跟Stopwatch差不多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Benchmark
{
    private static DateTime startDate = DateTime.MinValue;
    private static DateTime endDate = DateTime.MinValue;
 
    public static TimeSpan Span { get { return endDate.Subtract(startDate); } }
 
    public static void Start() { startDate = DateTime.Now; }
 
    public static void End() { endDate = DateTime.Now; }
 
    public static double GetSeconds()
    {
        if (endDate == DateTime.MinValue) return 0.0;
        else return Span.TotalSeconds;
    }
}

以Lockbits的方式访问bitmap的更多相关文章

  1. Linux实现https方式访问站点

    超文本传送协议(HyperText Transfer Protocol,HTML)是一种通信协议,它允许将超文本标记语言文档从web服务器传送到wel浏览器. HTML的特点: 1.支持客户/服务器模 ...

  2. SharePoint—用REST方式访问列表

    REST的定义与作用 在SharePoint 2010中,基本上有如下几种数据访问方式: 服务器端对象模型 LINQ to SharePoint Web Service 客户端对象模型 ADO.NET ...

  3. salesforce 零基础学习(三十三)通过REST方式访问外部数据以及JAVA通过rest方式访问salesforce

    本篇参考Trail教程: https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_ ...

  4. 非链接方式访问数据库--查询的数据集用Dataset来存储。

    private void Button_Click_1(object sender, RoutedEventArgs e) { //非链接方式访问数据库, //1创建连接对象(连接字符串) using ...

  5. ADO.NET 连接方式和非链接方式访问数据库

    一.//连接方式访问数据库的主要步骤(利用DataReader对象实现数据库连接模式) 1.创建连接对象(连接字符串) SqlConnection con = new SqlConnection(Co ...

  6. httpclient 认证方式访问http api/resutful api并获取json结果

    最近,因公司线上环境rabbitmq经常发生堆积严重的现象,于是跟运维组讨论,帮助开发个集中监控所有rabbitmq服务器运行情况的应用,需要通过java访问rabbitmq暴露的http api并接 ...

  7. php 面向对象的方式访问数据库

    <body> <?php //面向对象的方式访问数据库 //造对象 $db = new MySQLi("localhost","root",& ...

  8. URL方式访问Hadoop的内容

    * 1.设置url支持hadoop,FsUrlStreamHandlerFactory      * 2.创建URL对象,指定访问的HDFS路径      * 3.openStream获取输入流对象, ...

  9. 使用HttpWebRequest方式访问外部接口

    第一步,如果不是http网站,则需认证信托证书 /// <summary> /// 认证信托证书 /// </summary> /// <param name=" ...

随机推荐

  1. [drp 5] pageModel的建立,实现分页查询

    导读:之前做的分页,一直都是用的easy--UI分页,然后没有系统的整理过,就是知道传几个参数,然后云云.这次,从头到尾总结一下,了了我的这桩心愿.人事系统的重定向工作,一直刺激着我一定要总结总结这个 ...

  2. use python get information from one page

    #!/usr/bin/python read = file('thread-1554-1-1.html','r') wr = file('list','w') while 1: line=read.r ...

  3. SQL中删除某数据库所有trigger及sp

    SQL中删除某数据库所有trigger及sp   编写人:CC阿爸 2014-6-14 在日常SQL数据库的操作中,如何快速的删除所有trigger及sp呢 以下有三种方式可快速处理. --第一种 - ...

  4. 仿淘宝颜色属性选择展示代码(jQuery)

    模仿淘宝商品选择颜色和尺寸的效果,即选择商品颜色和尺寸的时候,把选择的颜色和尺寸放到一个页面容器里面,不足之处,还望指教. <!DOCTYPE HTML> <html lang=&q ...

  5. oracle函数和存储过程示例

    Function: --为了使产生的uuid符合rfc 4122的标准(http://tools.ietf.org/html/rfc4122),例如:a8f662b8-6e7a-13fe-e040-9 ...

  6. LevelDB源码之五Current文件\Manifest文件\版本信息

    版本信息有什么用?先来简要说明三个类的具体用途: Version:代表了某一时刻的数据库版本信息,版本信息的主要内容是当前各个Level的SSTable数据文件列表. VersionSet:维护了一份 ...

  7. 定时重启Apache与MySQL方法

    可以定时重启apache服务器等.让网站运行的效果更快. 采用at命令添加计划任务. 有关使用语法可以到window->“开始”->运行“cmd”->执行命令“at /”,这样界面中 ...

  8. js JSON对象属性

    json对象是是一种用于原生json分析的对象,无法对其进行构造函数调用,用java术语 来说,它相当于能够直接使用类方法的工具类JSON对象的属性parse(text[,reviver]);对参数t ...

  9. JS下高效拼装字符串的几种方法比较与测试代码

    在使用Ajax提交信息时,我可能常常需要拼装一些比较大的字符串通过XmlHttp来完成POST提交.尽管提交这样大的信息的做法看起来并不优雅,但有时我们可能不得不面对这样的需求.那么JavaScrip ...

  10. C语言警告:warning C4018: “<”: 有符号/无符号不匹配

    问题如下: 代码出问题之处:   原因分析: strlen返回一个无符号整型,也就是unsigned型,比较时应该两边的数据类型相同,故严格上来说,应该将m定义为unsigned型.       修改 ...