如何从矩形中获取图像?

时间:2015-05-01 08:25:35

标签: c# winforms system.drawing

我正在制作一个裁剪图像的程序。我有两个format="boolean" 和一个名为'crop'的按钮。一个图片框包含一个图像,当我在其中选择一个矩形并按“裁剪”时,所选区域出现在另一个图片框中;所以当我按下裁剪时程序正在运行。问题是:如何将裁剪区域的图像转换为图片框?

PictureBoxes

问题是 x = null 并且图片显示在图片框中,那么如何将此图片框中的图片放入 Rectangle rectCropArea; Image srcImage = null; TargetPicBox.Refresh(); //Prepare a new Bitmap on which the cropped image will be drawn Bitmap sourceBitmap = new Bitmap(SrcPicBox.Image, SrcPicBox.Width, SrcPicBox.Height); Graphics g = TargetPicBox.CreateGraphics(); g.DrawImage(sourceBitmap, new Rectangle(0, 0, TargetPicBox.Width, TargetPicBox.Height), rectCropArea, GraphicsUnit.Pixel); //Good practice to dispose the System.Drawing objects when not in use. sourceBitmap.Dispose(); Image x = TargetPicBox.Image; 变量?

1 个答案:

答案 0 :(得分:3)

有几个问题:

  • 首先也是最重要的一点:您对PictureBox.Image(属性)与Graphics 表面关联的PictureBox之间的关系感到困惑即可。 从Graphics获得的Control.CreateGraphics对象只能绘制到控件的表面上;通常不是你想要的;即使您这样做,通常也希望使用Painte.Graphics事件中执行此操作。

因此,当您的代码似乎工作时,它只会在表面上绘制非持久性像素。最小化/最大化,您将看到非持久性意味着什么..!

要更改Bitmap bmp,您需要将其与Grahics对象关联,如下所示:

Graphics g = Graphics.FromImage(bmp);

现在你可以进入它:

g.DrawImage(sourceBitmap, targetArea, sourceArea, GraphicsUnit.Pixel);

之后,您可以将Bitmap分配给Image的{​​{1}}属性..

最后处理TargetPicBox,或者更好,将其放入Graphics子句中。

我假设您已设法提供using有意义的值。

  • 另请注意,复制源位图的方式有错误:如果您需要完整图片,请使用 rectCropArea(*),而不是Size !!

  • 而不是使用相同的错误创建目标矩形,只需使用PictureBox

以下是裁剪按钮的示例代码:

TargetPicBox.ClientRectangle
  • 当然你应该在正确的鼠标事件中准备好Rectangle!
  • 在这里,您需要决定结果的宽高比;你可能不想扭曲结果!因此,您需要决定是否裁剪源裁剪矩形或是否展开目标矩形..!

请注意,由于我将 // a Rectangle for testing Rectangle rectCropArea = new Rectangle(22,22,55,99); // see the note below about the aspect ratios of the two rectangles!! Rectangle targetRect = TargetPicBox.ClientRectangle; Bitmap targetBitmap = new Bitmap(targetRect.Width, targetRect.Height); using (Bitmap sourceBitmap = new Bitmap(SrcPicBox.Image, SrcPicBox.Image.Width, SrcPicBox.Image.Height) ) using (Graphics g = Graphics.FromImage(targetBitmap)) g.DrawImage(sourceBitmap, targetRect, rectCropArea, GraphicsUnit.Pixel); if (TargetPicBox.Image != null) TargetPicBox.Dispose(); TargetPicBox.Image = targetBitmap; 分配给targetBitmap,我必须它!相反,在分配新的TargetPicBox.Image之前,我首先Image旧的Dispose