您的位置:首页 > 编程语言

朋友Zgke向我提供的有关截图和去除背景的源代码,大家有什么更好的意见或建议,交流交流

2011-10-07 15:46 615 查看
我想把


当中的红色给截取出来,并把红色部分背景去掉

一下是朋友提供的代码:

只在一个Program.cs中,注意文件路径和名称对应(如果你要试试程序的正确性)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices ;

namespace Zgkeprogram
{
class Program
{
static void Main(string[] args)
{
Bitmap _NewBitmap = (Bitmap)Image.FromFile(@"C:\Documents and Settings\Administrator\桌面\eegtest.bmp");//从指定的位置创建原始图像

//创建图形数据
BitmapData _Data = _NewBitmap.LockBits(new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height), ImageLockMode.ReadOnly, _NewBitmap.PixelFormat);

//创建一行RGB数据流  大小为_Data.Stride 一行
byte[] _ColorBytes = new byte[_Data.Stride];
//第1行的开始位置是 _Data.Scan0  图形第1行是黑色的无法使用  使用第2行 _StartPtr 为第2行的开始位置
IntPtr _StartPtr = new IntPtr(_Data.Scan0.ToInt32() + _Data.Stride);
//复制数据到RGB流
Marshal.Copy(_StartPtr, _ColorBytes, 0, _Data.Stride);
//释放锁定
_NewBitmap.UnlockBits(_Data);

int _StartWidth = 0; //红色的开始位置
bool _StartBool = true;//用于判断开始位置是否找到
int _EndWidth = 0;//红色的结束位置
bool _EndBool = true;//用于判断结束位置是否找到
int _EndIndex = _ColorBytes.Length - 1; //结束位置的索引
switch (_NewBitmap.PixelFormat)
{
case PixelFormat.Format32bppArgb://颜色的深度  32位==4byte[]
for (int i = 0; i != _NewBitmap.Width; i++)
{
if (_StartBool)
{//数据流为  B G R A    B G R A    B G R A   B G R A ........  B G R A      如果颜色 R>=200  并且 G  B 都小于50 就认为是红色
if (_ColorBytes[i * 4 + 2] >= 200 && _ColorBytes[i * 4 + 1] <= 50 && _ColorBytes[i * 4] <= 50)
{
_StartWidth = i;//记录开始位置
_StartBool = false;  //下次循环执行不在取位置
}
}

if (_EndBool)
{//这个和上面的不同 是倒这取B G R A 去行的最后开始向前循环  结束位置的索引 -1为R  -2为G   -3为B  判断规格同上
if (_ColorBytes[_EndIndex - (i * 4) - 1] >= 200 && _ColorBytes[_EndIndex - (i * 4) - 2] <= 50 && _ColorBytes[_EndIndex - (i * 4) - 3] <= 50)
{
_EndWidth = _NewBitmap.Width - i;//记录结束位置
_EndBool = false;
}
}
if (!_EndBool && !_StartBool) break;
}
break;
}
//创建新的图形       区域为   红色的开始位置   0    红色的结束位置-红色开始位置   图形高
Bitmap _SaveBitmap = _NewBitmap.Clone(new Rectangle(_StartWidth, 0, _EndWidth - _StartWidth, _NewBitmap.Height), _NewBitmap.PixelFormat);
_SaveBitmap.Save(@"C:\Documents and Settings\Administrator\桌面\111.bmp");
_SaveBitmap.MakeTransparent(Color.Red);//去掉红色背景色。
_SaveBitmap.Save(@"C:\Documents and Settings\Administrator\桌面\123.bmp");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐