使用 PictureBox 控件比较两个图像

Compare two images with PictureBox controls

我正在尝试实现类似于 this site 的效果。我基本上是在尝试实现一种方法来 "compare" 两个相似的图像(具有不同的颜色等)。我设法以一种不太聪明的方式做到了这一点,使用两个相邻的 PictureBox 控件 (Winforms),并在 MouseMove 事件中更改它们的 Size 和 Location 属性。

结果有效,但闪烁很多,这并不是最好的方法。 有没有更好的方法来做到这一点,也许使用 WPF 或以任何方式更改代码?这是:

private void pbImg1_MouseMove(object sender, MouseEventArgs e)
    {
        pbImg2.Image = CropImage(array[1], new Rectangle(pbImg1.Size.Width, 0, totalSize.Width - pbImg1.Size.Width, 240));
        pbImg1.Size = new Size(e.X, pbImg1.Height);
        pbImg2.Location = new Point(pbImg1.Size.Width + pbImg1.Location.X, pbImg2.Location.Y);
        pbImg2.Size = new Size(totalSize.Width - pbImg1.Size.Width, 240);

        lpbImg1Size.Text = pbImg1.Size.ToString();
        lpbImg2Size.Text = pbImg2.Size.ToString();
        lpbImg1Location.Text = pbImg1.Location.ToString();
        lpbImg2Location.Text = pbImg2.Location.ToString();
    }

private void pbImg2_MouseMove(object sender, MouseEventArgs e)
    {
        pbImg1.Image = CropImage(array[0], new Rectangle(0, 0, totalSize.Width - pbImg2.Size.Width, 240));
        pbImg1.Size = new Size(pbImg1.Width + e.X, 240);

        lpbImg1Size.Text = pbImg1.Size.ToString();
        lpbImg2Size.Text = pbImg2.Size.ToString();
        lpbImg1Location.Text = pbImg1.Location.ToString();
        lpbImg2Location.Text = pbImg2.Location.ToString();
    }

public Bitmap CropImage(Bitmap source, Rectangle section)
    {
        // An empty bitmap which will hold the cropped image

        //TRY CATCH
        Bitmap bmp = new Bitmap(section.Width, section.Height);

        Graphics g = Graphics.FromImage(bmp);

        // Draw the given area (section) of the source image
        // at location 0,0 on the empty bitmap (bmp)
        g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);

        return bmp;
    }

在这里您可以看到程序的行为: https://gfycat.com/VillainousReadyAmazonparrot

您需要两张图片imageLeft, imageRight 与图片框大小相同:

private int pos = 0; //x coordinate of mouse in picturebox

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if(pos == 0)
    {
        e.Graphics.DrawImage(Properties.Resources.imageRight, new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height));
    }
    else
    {
        e.Graphics.DrawImage(Properties.Resources.imageLeft, new Rectangle(0, 0, pos, pictureBox1.Height),
            new Rectangle(0, 0, pos, pictureBox1.Height), GraphicsUnit.Pixel);
        e.Graphics.DrawImage(Properties.Resources.imageRight, new Rectangle(pos, 0, pictureBox1.Width - pos, pictureBox1.Height),
            new Rectangle(pos, 0, pictureBox1.Width - pos, pictureBox1.Height), GraphicsUnit.Pixel);
    }
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    pos = e.X;
    pictureBox1.Invalidate();
}