从Graphics调整图像大小?

4

我试图在从屏幕复制图像后调整其大小,但不知道该如何操作。我阅读的教程建议使用Graphics.DrawImage来调整图像大小,但是当我运行此代码时,它没有调整大小。

Bitmap b = new Bitmap(control.Width, control.Height);
Graphics g = Graphics.FromImage(b);
g.CopyFromScreen(control.Parent.RectangleToScreen(control.Bounds).X, control.Parent.RectangleToScreen(control.Bounds).Y, 0, 0, new Size(control.Bounds.Width, control.Bounds.Height), CopyPixelOperation.SourceCopy);

g.DrawImage(b, 0,0,newWidth, newHeight);

非常感谢您的帮助!以下是相关的IT技术内容翻译:


你希望调整大小后的图像放在哪里?你有一个位图,但实际上并没有使用它,然后又有一张图片在你的代码块中没有被定义。 - Jamie Treworgy
哎呀,我写错了一些代码,还复制了其他的代码,现在不一致了,谢谢你指出来。我马上会修正我的帖子。 - sooprise
2个回答

6
尝试这个。当您使用DrawImage时,图形不会“替换”图像-它会在其源上绘制输入图像,这与您尝试绘制到其上的图像相同。可能有更简洁的方法来实现这一点,但是......
Bitmap b = new Bitmap(control.Width, control.Height);
using (Graphics g = Graphics.FromImage(b)) {
   g.CopyFromScreen(control.Parent.RectangleToScreen(control.Bounds).X, 
      control.Parent.RectangleToScreen(control.Bounds).Y, 0, 0, 
      new Size(control.Bounds.Width, control.Bounds.Height),
      CopyPixelOperation.SourceCopy);
}
Bitmap output = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(output)) {
  g.DrawImage(b, 0,0,newWidth, newHeight);
}

1
需要一些 using 块。必须处理 Graphics 对象。在 g 被处理之前,b 中可能什么也没有。 - Ben Voigt
哈哈,我刚在另一个与数据读取器有关的问题中赞扬“使用”的优点。你是正确的先生,已更新。 - Jamie Treworgy
使用块后,图形对象是否仍需要处理? - sooprise
使用using会自动调用Dispose()方法,这也是它存在的目的。 - Jamie Treworgy

0

你为什么不能直接使用PictureBox控件呢?那个控件会自动帮你拉伸大小。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接