作者icools (icools)
看板C_Sharp
标题[心得] 将Bitmap 转为Color[,] 处理在转回分享
时间Fri Mar 14 05:54:00 2008
大家应该都知道 GetPixel / SetPixel 的方式不适合用在大量存取
所以都会改用指标 unsafe 的方式来处理
我一开始也这样,後来发现指标要对某个pixel的上下左右pixel 存取非常不方便(要计算)
常常不小心就会存取到不可存取记忆体区域
後来我就想说写一个方法,一次从指标中读出
也就是
Color[,] cr= ConverBitmap2Array(bmp) ;
如此只需要使用两个回圈
for(...)
{
for(...)
{
//cr[i,j].R = 230 ; cr[i,j].G =100 ; ...
}
}
大概就是之前 C++ 之类处理的方式
处理完後...
Bitmap bmp2 = ConverArray2Bitmap(cr);
就可以取得处理过後的图
不是什麽特殊的东西,不过我写的时候卡在 width 和 height 回圈位置搞错没发现 (记忆体会有相关)
不过终於是好了 XD
有兴趣可以从我的 sky dirve下载
http://cid-c1df0d75fca0a538.skydrive.live.com/self.aspx/%e5%85%ac%e9%96%8b/Bitmap2Array.cs
(cs档不能直接用,我是直接把这两个method 贴到文字档上面而已 XD ,其他的类别架构自己补一下 )
下面供参考...
/// <summary>
/// 将bitmap 直接转成二维array 资料
/// </summary>
/// <param name="bmpSrc"></param>
/// <returns></returns>
public static Color[,] ConvertBitmap2Array(Bitmap bmpSrc)
{
// get size
int width = bmpSrc.Width;
int height = bmpSrc.Height;
// array data
Color[,] ad = new Color[width, height];
// lockBits
BitmapData dataS = bmpSrc.LockBits(new Rectangle(0, 0, width,
height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
unsafe
{
// get remain
int remain1 = dataS.Stride - dataS.Width * 3;
// get ptr point
byte* ptr1 = (byte*)dataS.Scan0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
ad[j, i] = Color.FromArgb(ptr1[2], ptr1[1],
ptr1[0]);
ptr1 += 3;
}
ptr1 += remain1;
}
}
// unLock
bmpSrc.UnlockBits(dataS);
return ad;
}
/// <summary>
/// 将Array 直接转成 Bitmap
/// </summary>
public static Bitmap ConvertArray2Bitmap(Color[,] ad)
{
// get size
int width = ad.GetLength(0);
int height = ad.GetLength(1);
Bitmap bmpSrc = new Bitmap(width,
height,PixelFormat.Format24bppRgb);
// lockBits
BitmapData dataS = bmpSrc.LockBits(new Rectangle(0, 0, width,
height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
unsafe
{
// get remain
int remain1 = dataS.Stride - dataS.Width * 3;
// get ptr point
byte* ptr1 = (byte*)dataS.Scan0;
for (int i = 0; i <height ; i++)
{
for (int j = 0; j < width; j++)
{
ptr1[0] = ad[j, i].B;
ptr1[1] = ad[j, i].G;
ptr1[2] = ad[j, i].R;
ptr1 += 3;
}
//cross remain mem
ptr1 += remain1;
}
}
// unLock
bmpSrc.UnlockBits(dataS);
return bmpSrc;
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 203.68.164.51
1F:推 cczeke:非常受用 感谢 ^^ 03/14 10:57
2F:推 tomex:建议操作unsafe指标时,加上fixed关键字比较好!! 03/14 17:21