使用PictureBox控件比较两个图像

时间:2015-01-02 17:35:02

标签: c# image winforms comparison picturebox

我正试图达到类似this site的效果。我基本上试图实现一种“比较”两个相似图像(具有不同颜色等)的方法。我设法以一种不太好的方式执行此操作,使用两个PictureBox控件(Winforms),并在MouseMove事件上更改其大小和位置属性。

结果有效,但它会闪烁很多,并不是最好的方法。 有没有更好的方法来做到这一点,可能是使用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

1 个答案:

答案 0 :(得分:0)

您需要两张与图片框大小相同的 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();
}