如何裁剪图像并调整大小

Graphics 类提供了多种 DrawImage 方法,其中一些方法具有可用于裁剪和缩放图像的源和目标矩形参数。

示例:

以下示例从磁盘文件 Apple.gif构造对象 Image 。 代码以原始大小绘制整个苹果图像。 然后,代码调用 DrawImage 对象的 Graphics 方法,在一个比原始苹果图像更大的目标矩形中绘制苹果图像的一部分。

该方法 DrawImage 通过查看源矩形来确定要绘制的苹果的哪个部分,该矩形由第三个、第四个、第五个和第六个参数指定。 在这种情况下,苹果的宽度裁剪为75%,高度为75%。

DrawImage 方法通过查看由第二个参数指定的目标矩形区域来确定裁剪后的苹果应该放置的位置以及大小。 在这种情况下,目标矩形比原始图像宽 30%,高 30%。

下图显示了原始苹果和缩放且裁剪后的苹果。

原始图像的屏幕截图以及同一图像被裁剪后的屏幕截图。

Image image = new Bitmap("Apple.gif");

// Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0);

// Make the destination rectangle 30 percent wider and
// 30 percent taller than the original image.
// Put the upper-left corner of the destination
// rectangle at (150, 20).
int width = image.Width;
int height = image.Height;
RectangleF destinationRect = new RectangleF(
    150,
    20,
    1.3f * width,
    1.3f * height);

// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
RectangleF sourceRect = new RectangleF(0, 0, .75f * width, .75f * height);
e.Graphics.DrawImage(
    image,
    destinationRect,
    sourceRect,
    GraphicsUnit.Pixel);
Dim image As New Bitmap("Apple.gif")

' Draw the image unaltered with its upper-left corner at (0, 0).
e.Graphics.DrawImage(image, 0, 0)

' Make the destination rectangle 30 percent wider and
' 30 percent taller than the original image.
' Put the upper-left corner of the destination
' rectangle at (150, 20).
Dim width As Integer = image.Width
Dim height As Integer = image.Height
Dim destinationRect As New RectangleF( _
    150, _
    20, _
    1.3F * width, _
    1.3F * height)

' Draw a portion of the image. Scale that portion of the image
' so that it fills the destination rectangle.
Dim sourceRect As New RectangleF(0, 0, 0.75F * width, 0.75F * height)
e.Graphics.DrawImage( _
    image, _
    destinationRect, _
    sourceRect, _
    GraphicsUnit.Pixel)

编译代码

前面的示例设计用于 Windows 窗体,它需要 PaintEventArgse,这是 Paint 事件处理程序的参数。 请确保将 Apple.gif 替换为在您系统上有效的图像文件名和路径。

另请参阅