我希望得到两张图片之间的区别
我使用这个源代码:
public Bitmap GetDifference(Bitmap bm1, Bitmap bm2)
{
if (bm1.Size != bm2.Size)
throw new ArgumentException("exception");
var resultImage = new Bitmap(bm1.Width, bm1.Height);
using (Graphics g = Graphics.FromImage(resultImage))
g.Clear(Color.Transparent);
for (int w = 0; w < bm1.Width; w++)
{
for (int h = 0; h < bm1.Height; h++)
{
var bm2Color = bm2.GetPixel(w, h);
if (IsColorsDifferent(bm1.GetPixel(w, h), bm2Color))
{
resultImage.SetPixel(w, h, bm2Color);
}
}
}
return resultImage;
}
bool IsColorsDifferent(Color c1, Color c2)
{
return c1 != c2;
}
这个来源对我很有用,但我有以下问题:
如果我选择分辨率为480x320的图像,我的resultImage具有相同的分辨率(这是核心,因为我在创建新的Bitmap时设置),但是我的图像具有透明色,我想获得带有纯色。
让我们说 - 如果480x320中的实体结果图像(纯色像素)具有100x100场,我应该得到分辨率为100x100的这个实心位图。
简而言之,我只需要获得一个带有纯色和alpha字母切割边框的矩形。
谢谢!
答案 0 :(得分:0)
请参阅我在下面写的课程:
class ProcessingImage
{
public Bitmap GetDifference(Bitmap bm1, Bitmap bm2)
{
if (bm1.Size != bm2.Size)
throw new ArgumentException("Images must have one size");
var resultImage = new Bitmap(bm1.Width, bm1.Height);
using (Graphics g = Graphics.FromImage(resultImage))
g.Clear(Color.Transparent);
int min_height = int.MaxValue;
int min_width = int.MaxValue;
int max_height = -1;
int max_width = -1;
for (int w = 0; w < bm1.Width; w++)
for (int h = 0; h < bm1.Height; h++)
{
var bm2Color = bm2.GetPixel(w, h);
if (IsColorsDifferent(bm1.GetPixel(w, h), bm2Color))
{
resultImage.SetPixel(w, h, bm2Color);
if (h < min_height) min_height = h;
if (w < min_width) min_width = w;
if (h > max_height) max_height = h;
if (w > max_width) max_width = w;
}
}
max_height = max_height + 1; //Needed for get valid max height point, otherwise we lost one pixel.
max_width = max_width + 1; //Needed for get valid max width point, otherwise we lost one pixel.
// Calculate original size for image without alpha chanel.
int size_h = max_height - min_height;
int size_w = max_width - min_width;
var resizeImage = new Bitmap(size_w, size_h); // Creaete bitmap with new size.
for (int w = 0; w < resultImage.Width; w++)
for (int h = 0; h < resultImage.Height; h++)
{
var color = resultImage.GetPixel(w, h);
if (color.A != 0)
{
// Move each pixels at a distance calculate before.
int x = w - min_width;
int y = h - min_height;
resizeImage.SetPixel(x, y, color);
}
}
return resizeImage;
}
bool IsColorsDifferent(Color c1, Color c2)
{
return c1 != c2;
}
}
我认为,这个类可以修改为优化,但现在它运行良好。如果您需要具有原始大小且没有Alpha通道的返回图像 - 这是许多解决方案之一。如何做到这一点。