现在的位置: 首页 > 综合 > 正文

.NET 中裁切和缩放图像

2013年10月09日 ⁄ 综合 ⁄ 共 2318字 ⁄ 字号 评论关闭

        可以使用 Graphics 类的 DrawImage 方法来绘制并定位矢量图像和光栅图像。DrawImage 是一种重载方法,因此您有数种方式为它提供参数。DrawImage 方法的一种变体接收 Bitmap 对象和 Rectangle 对象。该矩形指定了绘图操作的目标,即它指定了将要在其内绘图的矩形。如果目标矩形的大小与原始图像的大小不同,原始图像将进行缩放,以适应目标矩形。下面的示例将同一图像绘制了三次:一次没有缩放,一次使用扩展,一次使用压缩:

[Visual Basic]
Dim myBitmap As New Bitmap("Spiral.png")
      
Dim expansionRectangle As New Rectangle(135, 10, _
   myBitmap.Width, myBitmap.Height)

Dim compressionRectangle As New Rectangle(300, 10, _
   myBitmap.Width / 2, myBitmap.Height / 2)

myGraphics.DrawImage(myBitmap, 10, 10)
myGraphics.DrawImage(myBitmap, expansionRectangle)
myGraphics.DrawImage(myBitmap, compressionRectangle)
[C#]
Bitmap myBitmap = new Bitmap("Spiral.png");

Rectangle expansionRectangle = new Rectangle(135, 10,
   myBitmap.Width, myBitmap.Height);

Rectangle compressionRectangle = new Rectangle(300, 10,
   myBitmap.Width / 2, myBitmap.Height/2);

myGraphics.DrawImage(myBitmap, 10, 10);
myGraphics.DrawImage(myBitmap, expansionRectangle);
myGraphics.DrawImage(myBitmap, compressionRectangle);

下面的插图显示了这三张图片。

DrawImage 方法的一些变体带有源矩形参数和目标矩形参数。源矩形参数指定原始图像要绘制的部分。目标矩形参数指定将要在其内绘制该图像指定部分的矩形。如果目标矩形的大小与源矩形的大小不同,图片将会缩放,以适应目标矩形。

下面的示例从文件 Runner.jpg 中构造 Bitmap 对象。整个图像绘制时在 (0,0) 处没有缩放。然后将该图像的一小部分绘制两次:一次使用压缩,一次使用扩展。

[Visual Basic]
Dim myBitmap As New Bitmap("Runner.jpg")

' One hand of the runner
Dim sourceRectangle As New Rectangle(80, 70, 80, 45)

' Compressed hand
Dim destRectangle1 As New Rectangle(200, 10, 20, 16)

' Expanded hand
Dim destRectangle2 As New Rectangle(200, 40, 200, 160)

' Draw the original image at (0, 0).
myGraphics.DrawImage(myBitmap, 0, 0)

' Draw the compressed hand.
myGraphics.DrawImage( _
   myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel)

' Draw the expanded hand. 
myGraphics.DrawImage( _
   myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel)
[C#]
Bitmap myBitmap = new Bitmap("Runner.jpg"); 

// One hand of the runner
Rectangle sourceRectangle = new Rectangle(80, 70, 80, 45);

// Compressed hand
Rectangle destRectangle1 = new Rectangle(200, 10, 20, 16);

// Expanded hand
Rectangle destRectangle2 = new Rectangle(200, 40, 200, 160);

// Draw the original image at (0, 0).
myGraphics.DrawImage(myBitmap, 0, 0);

// Draw the compressed hand.
myGraphics.DrawImage(
   myBitmap, destRectangle1, sourceRectangle, GraphicsUnit.Pixel);

// Draw the expanded hand. 
myGraphics.DrawImage(
   myBitmap, destRectangle2, sourceRectangle, GraphicsUnit.Pixel);

下面的插图显示了未缩放的图像,以及压缩的和扩展的图像部分。

如何在图片中用程序自动加上水印?知道的朋友请一定告诉我啊 :-)

抱歉!评论已关闭.