有时候会遇到有两张几乎完全相同的图片,但其中一张会多一些东西,比如logo、花纹等。此程序可以找到这些不同,将图片不同的像素放到另一张图片上
例如:
程序界面如下图
点击文件1按钮加载第一个图片,文件2同理,点击【开始比较】按钮,会生成一张新的图片,即两个图片之间的差异(文件1多于文件2的部分)
主要问题在对于图片像素的处理(按下【开始比较】按钮的处理)
程序压缩包见如下链接
http://download.csdn.net/detail/u013218907/9500550
核心代码如下:
private void btnStartCompare_Click(object sender, EventArgs e)
{
Bitmap bitmap1 = (Bitmap)Bitmap.FromFile(this.tbxFilePath1.Text, false);
Bitmap bitmap2 = (Bitmap)Bitmap.FromFile(this.tbxFilePath2.Text, false);
Bitmap diffBitmap = createBitmap(bitmap1.Width, bitmap1.Height);
//检查图片
if (!checkBitmap(bitmap1, bitmap2))
{
MessageBox.Show(this, "图片有问题", "警告",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
compareBitmap(bitmap1, bitmap2, diffBitmap);
try
{
diffBitmap.Save("diff.png");
}
catch (Exception)
{
MessageBox.Show(this, "存储图片时发生错误〒_〒", "出错了",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show(this, "成功完成图片处理~", "成功了!!!",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private bool checkBitmap(Bitmap bitmap1, Bitmap bitmap2)
{
if (bitmap1 == null || bitmap2 == null) {
return false;
}
if (bitmap1.Width != bitmap2.Width || bitmap1.Height != bitmap2.Height)
{
return false;
}
return true;
}
private void compareBitmap(Bitmap bitmap1, Bitmap bitmap2, Bitmap diffBitmap)
{
Color color1;
Color color2;
int wide = bitmap1.Width;
int height = bitmap1.Height;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < wide; x++)
{
//获取像素的RGB颜色值
color1 = bitmap1.GetPixel(x, y);
color2 = bitmap2.GetPixel(x, y);
if (color1 != color2)
{
diffBitmap.SetPixel(x, y, color1);
}
}
}
return;
}
private Bitmap createBitmap(int wight, int height)
{
Bitmap bitmap = new Bitmap(wight, height);
bitmap.MakeTransparent(Color.Transparent);
return bitmap;
}
public static Bitmap RGB2Gray(Bitmap srcBitmap)
{
Color srcColor;
int wide = srcBitmap.Width;
int height = srcBitmap.Height;
for (int y = 0; y < height; y++)
for (int x = 0; x < wide; x++)
{
//获取像素的RGB颜色值
srcColor = srcBitmap.GetPixel(x, y);
byte temp = (byte)(srcColor.R * .299 + srcColor.G * .587 + srcColor.B * .114);
//设置像素的RGB颜色值
srcBitmap.SetPixel(x, y, Color.FromArgb(temp, temp, temp));
}
return srcBitmap;
}
}