我正在制作一个裁剪图像的程序。我有两个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;
变量?
答案 0 :(得分:3)
有几个问题:
PictureBox.Image
(属性)与Graphics
表面关联的PictureBox
之间的关系感到困惑即可。
从Graphics
获得的Control.CreateGraphics
对象只能绘制到控件的表面上;通常不是你想要的;即使您这样做,通常也希望使用Paint
在e.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
请注意,由于我将 // 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
。