【问题标题】:Select Area of Image选择图像区域
【发布时间】:2013-01-10 08:28:40
【问题描述】:

我正在尝试选择我使用 openfiledialog 选择的图像区域 我要选择的区域是 x,y 坐标 5,5 的 16x16 选择后,我想将 16x16 图像绘制到坐标 0,0 处的另一个图片框

这是我得到的代码,但我无法让它选择原始图像的正确部分,有人对它为什么不起作用有任何建议吗?

DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
    Image origImage = Image.FromFile(openFileDialog1.FileName);
    pictureBoxSkin.Image = origImage;
    lblOriginalFilename.Text = openFileDialog1.SafeFileName;

    System.Drawing.Bitmap bmp = new Bitmap(16, 16);
    Graphics g3 = Graphics.FromImage(bmp);
    g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);

    Graphics g2 = pictureBoxNew.CreateGraphics();
    g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);
}

【问题讨论】:

  • 您能否详细说明它是如何不工作的?
  • 使用 Graphics.DrawImage(Image, Rectangle, Rectangle, GraphicsUnit) 重载。

标签: c# .net image gdi+


【解决方案1】:

为了选择正确的部分,只需替换:

g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);

与

g3.DrawImageUnscaled(origImage, -5, -5, 16, 16);

【讨论】:

  • 负坐标,完美!谢谢。
【解决方案2】:

替换这个:

Graphics g2 = pictureBoxNew.CreateGraphics();
g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);

用这个:

pictureBoxNew.Image = bmp;

你很好。

完整代码:

DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
    Image origImage = Image.FromFile(openFileDialog1.FileName);
    pictureBoxSkin.Image = origImage;
    lblOriginalFilename.Text = openFileDialog1.SafeFileName;

    System.Drawing.Bitmap bmp = new Bitmap(16, 16);
    Graphics g3 = Graphics.FromImage(bmp);
    g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);

    pictureBoxNew.Image = bmp;
    //Graphics g2 = pictureBoxNew.CreateGraphics();
    //g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);
}

当您在Paint 事件之外的任何地方绘制东西时,它会在需要再次绘制控件时立即删除(即,当从最小化状态恢复时,另一个窗口会越过您的窗口,或者您调用Refresh 方法)。因此,将控件的绘图代码放在其Paint 事件中,或者让控件管理图像的绘制(在本例中,将Image 分配给PictureBox 控件)。

【讨论】:

  • 我需要保留 Graphics g2 部分,因为在下一个循环中,坐标需要更改到另一个位置。我会考虑为图像添加绘画事件。
猜你喜欢
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
相关资源
最近更新 更多