引言

在对Bitmap图片操作的时候,有时需要用到获取或设置像素颜色方法:GetPixel 和 SetPixel,

如果直接对这两个方法进行操作的话速度很慢,这里我们可以通过把数据提取出来操作,然后操作完在复制回去可以加快访问速度

两种方法

其实对Bitmap的访问还有两种方式,一种是内存法,一种是指针法

1、内存法

  这里定义一个类LockBitmap,通过把Bitmap数据拷贝出来,在内存上直接操作,操作完成后在拷贝到Bitmap中

        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
Rectangle rect = new 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;
}
}
}

  使用:先锁定Bitmap,然后通过Pixels操作颜色对象,最后释放锁,把数据更新到Bitmap中

            string file = @"C:\test.jpg";
Bitmap bmp = new Bitmap(Image.FromFile(file)); LockBitmap lockbmp = new LockBitmap(bmp);
//锁定Bitmap,通过Pixel访问颜色
lockbmp.LockBits(); //获取颜色
Color color = lockbmp.GetPixel(10, 10); //从内存解锁Bitmap
lockbmp.UnlockBits();

 2、指针法

  这种方法访问速度比内存法更快,直接通过指针对内存进行操作,不需要进行拷贝,但是在C#中直接通过指针操作内存是不安全的,所以需要在代码中加入unsafe关键字,在生成选项中把允许不安全代码勾上,才能编译通过

  这里定义成PointerBitmap类

            public class PointBitmap
{
Bitmap source = null;
IntPtr Iptr = IntPtr.Zero;
BitmapData bitmapData = null; public int Depth { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; } public PointBitmap(Bitmap source)
{
this.source = source;
} 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
Rectangle rect = new 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); //得到首地址
unsafe
{
Iptr = bitmapData.Scan0;
//二维图像循环 }
}
catch (Exception ex)
{
throw ex;
}
} public void UnlockBits()
{
try
{
source.UnlockBits(bitmapData);
}
catch (Exception ex)
{
throw ex;
}
} public Color GetPixel(int x, int y)
{
unsafe
{
byte* ptr = (byte*)Iptr;
ptr = ptr + bitmapData.Stride * y;
ptr += Depth * x / 8;
Color c = Color.Empty;
if (Depth == 32)
{
int a = ptr[3];
int r = ptr[2];
int g = ptr[1];
int b = ptr[0];
c = Color.FromArgb(a, r, g, b);
}
else if (Depth == 24)
{
int r = ptr[2];
int g = ptr[1];
int b = ptr[0];
c = Color.FromArgb(r, g, b);
}
else if (Depth == 8)
{
int r = ptr[0];
c = Color.FromArgb(r, r, r);
}
return c;
}
} public void SetPixel(int x, int y, Color c)
{
unsafe
{
byte* ptr = (byte*)Iptr;
ptr = ptr + bitmapData.Stride * y;
ptr += Depth * x / 8;
if (Depth == 32)
{
ptr[3] = c.A;
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
else if (Depth == 24)
{
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
else if (Depth == 8)
{
ptr[2] = c.R;
ptr[1] = c.G;
ptr[0] = c.B;
}
}
}
}

使用方法这里就不列出来了,跟上面的LockBitmap类似

资料

http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp

加快Bitmap的访问速度的更多相关文章

  1. C#加快Bitmap的访问速度

    在对Bitmap图片操作的时候,有时需要用到获取或设置像素颜色方法:GetPixel 和 SetPixel, 如果直接对这两个方法进行操作的话速度很慢,这里我们可以通过把数据提取出来操作,然后操作完在 ...

  2. .net 反射访问私有变量和私有方法 如何创建C# Closure ? C# 批量生成随机密码,必须包含数字和字母,并用加密算法加密 C#中的foreach和yield 数组为什么可以使用linq查询 C#中的 具名参数 和 可选参数 显示实现接口 异步CTP(Async CTP)为什么那样工作? C#多线程基础,适合新手了解 C#加快Bitmap的访问速度 C#实现对图片文件的压

    以下为本次实践代码: using System; using System.Collections.Generic; using System.ComponentModel; using System ...

  3. Apache 使用gzip、deflate 压缩页面加快网站访问速度

    Apache 使用gzip 压缩页面加快网站访问速度 介绍: 网页压缩来进一步提升网页的浏览速度,它完全不需要任何的成本,只不过是会让您的服务器CPU占用率稍微提升一两个百分点而已或者更少.   原理 ...

  4. [技术博客]使用CDN加快网站访问速度

    [技术博客]使用CDN加快网站访问速度 2s : most users are willing to wait 10s : the limit for keeping the user's atten ...

  5. 2-12-配置squid代理服务器加快网站访问速度

    本节所讲内容: squid服务器常见概念 squid服务器安装及相关配置文件 实战:配置squid正向代理服务器 实战:配置透明squid代理提升访问速度 实战:配置squid反向代理加速度内网web ...

  6. maven中央仓库访问速度太慢的解决办法

    方法一:修改settings.xml eclipse中集成的maven的settings.xml文件,找了半年也没找到,我们放弃eclipse中的maven,下一个最新的maven,并在eclipse ...

  7. Nginx——使用 Nginx 提升网站访问速度【转载+整理】

    原文地址 本文是写于 2008 年,文中提到 Nginx 不支持 Windows 操作系统,但是现在它已经支持了,此外还支持 FreeBSD,Solaris,MacOS X~ Nginx(" ...

  8. 使用 Nginx 提升网站访问速度

    使用 Nginx 提升网站访问速度 http://www.ibm.com/developerworks/cn/web/wa-lo-nginx/ Nginx 简介 Nginx ("engine ...

  9. 使用PHP和GZip压缩网站JS/CSS文件加速网站访问速度

    使用PHP和GZip压缩网站JS/CSS文件加速网站访问速度 一些泛WEB 2.0网站为了追求用户体验,可能会大量使用CSS和JS文件.这就导致在服务器带宽一定的情况下,多用户并发访问速度变慢.如何加 ...

随机推荐

  1. Android Studio安装genymotion模拟器

    1.Genymotion的安装: Genymotion无疑是目前最快最好用的模拟器.官网下载地址:https://www.genymotion.com/ 先注册,然后下载,安装VirtualBox最简 ...

  2. Android 网络开发免费API接口

    http://www.juhe.cn/                              聚合数据              目前很多接口都收费 https://www.showapi.com ...

  3. Unity3d动画脚本 Animation Scripting(深入了解游戏引擎中的动画处理原理)

    也许这一篇文章的内容有点枯燥,但我要说的是如果你想深入的了解游戏引擎是如何处理动画片断或者素材并 让玩家操控的角色动起来栩栩如生,那么这真是一篇好文章(当然我仅仅是翻译了一下)   动画脚本 Anim ...

  4. linux 禁ping本机方法

    linux 禁ping本机方法 禁ping执行:echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all 恢复ping 执行:echo 0 > /p ...

  5. centos7 配置vnc

    这是一个关于怎样在你的 CentOS 7 上安装配置 VNC 服务的教程.当然这个教程也适合 RHEL 7 .在这个教程里,我们将学习什么是 VNC 以及怎样在 CentOS 7 上安装配置 VNC ...

  6. 使用NHibernate(8)-- 延迟加载

    1,延迟加载. 延迟加载,即用到的时候再加载数据.这种机制是非常有情怀的,比如一篇中的用户实体有标签.问题等导航属性,如果只是用到用户名去查询整个实体,则把相关的标签和问题也都加载,性能会比较低.而有 ...

  7. Hyper-V的使用方法

    win8和win8.1以及win10自带虚拟机,无需再装第三方虚拟机软件. 首先需要在“启用或关闭windows功能”中,启用Hyper-V

  8. 【笔记】select2的使用

    <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Cont ...

  9. [MSSQL2012]First_Value函数

    First_Value返回结果集中某列第一条数据的值,跟TOP 1效果一样,比较简单的一个函数 先贴测试用代码 DECLARE @TestData TABLE(     ID INT IDENTITY ...

  10. HTML5 canvas globalCompositeOperation绘图类型讲解

    我们总是将一个图形画在另一个之上,大多数情况下,这样是不够的.比如说,它这样受制于图形的绘制顺序.不过,我们可以利用 globalCompositeOperation 属性来改变这些做法.global ...