【问题标题】:How to get an image from a rectangle?如何从矩形中获取图像?
【发布时间】:2015-07-11 02:26:39
【问题描述】:

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

 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;

问题是 x = null 并且图像显示在图片框中,那么我怎样才能从这个图片框中获取图像到 Image 变量中?

【问题讨论】:

    标签: c# winforms system.drawing


    【解决方案1】:

    几个问题:

    • 首先也是最重要的:您对PictureBox.Image(属性)和与PictureBox表面 关联的Graphics 之间的关系感到困惑。 从Control.CreateGraphics 得到的Graphics 对象只能在控件的表面上绘制;通常不是你想要的;即使你这样做了,你通常也想在 Paint 事件中使用 e.Graphics..

    因此,虽然您的代码似乎可以工作,但它只会在表面上绘制非持久像素。最小化/最大化,你就会明白非持久化意味着什么......!

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

    Graphics g = Graphics.FromImage(bmp);
    

    现在你可以画进去了:

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

    之后,您可以将Bitmap 分配给TargetPicBoxImage 属性..

    最后处理掉Graphics,或者更好,把它放到using 子句中..

    我假设您已设法为 rectCropArea 赋予有意义的值。

    • 另请注意,您复制源位图的方式有一个错误:如果您想要完整的图像,请使用 its Size (*),而不是 @ 之一987654339@!!

    • 而不是创建一个目标矩形,同样的错误,只需使用TargetPicBox.ClientRectangle

    这是裁剪按钮的示例代码:

     // 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;
    
    • 当然,您应该在适当的鼠标事件中准备好矩形!
    • 在这里您需要决定结果的纵横比;你可能不想扭曲结果!所以你需要决定是裁剪源裁剪矩形还是扩展目标矩形..!
    • 除非您确定 dpi 分辨率,否则您应该使用 SetResolution 来确保新图像具有相同的分辨率!

    请注意,由于我将targetBitmap 分配给TargetPicBox.Image,因此我必须 丢弃它!相反,在分配新的Image 之前,我先Dispose 旧的..

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 2017-08-03
      • 2011-12-17
      • 2014-12-22
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多