如何垂直合并图像



我有这段代码,但不起作用。我正试图从一个包含captcha的网站中提取一张图片。

var width = Images.First().Image.Width; //all images in list have the same width so i take the first
var height = 0;
for (int i = 104; i < 140; i++) //the list has 300 images. I have to get 36 that contains the captcha separated into pieces
{
height += Images[i].Image.Height; 
}
var bitmap2 = new Bitmap(width, height);
var g = Graphics.FromImage(bitmap2);
height = 0;
for (int i = 104; i < 140; i++)  
{
Image image = Images[i].Image;
g.DrawImage(image, 0, height);
height += image.Height;
}
bitmap2.Save(@"C:UsersuserDesktoptesttest.png", ImageFormat.Png);

有了这个代码,我得到了这个结果:

图像

我不知道为什么质量不好。我认为这是在重复记录在结果位图中的图像

我可以在代码中看到一些次优的东西,但老实说,没有一件东西能给出这样的结果。遇到这种问题的唯一方法是,如果你扰乱了原始后端,并执行了将数据解释为图像的操作。

代码中唯一需要修复的两件具体事情似乎是:

  • 将所有图像的分辨率设置为相同的值。这会影响它们的绘制大小,因此可能会打乱定位
  • 在完成Graphics对象之后关闭它,这样在尝试保存任何内容之前,所有更改都会被确认完成

请注意,在我调整后的代码中,images只是一个List<Bitmap>,for循环只是遍历它们。您从未指定Images集合的类型,这对我来说更容易测试。

Int32 width = Images.First().Width;
Int32 height = 0;
for (Int32 i = 0; i < Images.Count; i++)
{
height += Images[i].Height;
}
Bitmap bitmap2 = new Bitmap(width, height);
bitmap2.SetResolution(72, 72); // <-- Set explicit resolution on bitmap2
// Always put Graphics objects in a 'using' block.
using (Graphics g = Graphics.FromImage(bitmap2))
{
height = 0;
for (Int32 i = 0; i < Images.Count; i++)
{
Bitmap image = Images[i];
image.SetResolution(72, 72); // <-- Set resolution equal to bitmap2
g.DrawImage(image, 0, height);
height += image.Height;
}
}
bitmap2.Save(@"C:UsersuserDesktoptesttest.png", ImageFormat.Png);

最新更新