This example shows how to draw a cropped image from a file. In this instance we're going to discard a 20 pixel border round the edge of the image.

 

   
1
 
Setting Up    
     

We start by setting up variables we will use later - the path to the source file and the path to the output file.

[Visual Basic]
Dim inpath, outpath As String
inpath = Server.MapPath("rez/birds.jpg")
outpath = Server.MapPath("croppedbirds.jpg")

[C#]
string inpath = Server.MapPath("rez/birds.jpg");
string outpath = Server.MapPath("croppedbirds.jpg");

 

   
2
 
Creating the Objects    
     

We will need a few objects so we create them all here for convenience.

[Visual Basic]
Dim gr As New Graphic
Dim rc As New XRect
Dim ca As New Canvas

[C#]
Graphic gr = new Graphic();
XRect rc = new XRect();
Canvas ca = new Canvas();

 

   
3
 
Finding the Portion of the Image to Draw    
     

We need to find the portion of the image we want to draw. To do this we get the natural Rectangle of the main image using the Graphic object. We then inset the Rectangle by 20 pixels on each side.

[Visual Basic]
gr.SetFile(inpath)
If gr.Drawable Then
  rc.String = gr(0).Rectangle
  rc.Top = rc.Top + 20
  rc.Left = rc.Left + 20
  rc.Bottom = rc.Bottom - 20
  rc.Right = rc.Right - 20

[C#]
gr.SetFile(inpath);
if (gr.Drawable) {
  rc.String = gr[0].Rectangle;
  rc.Top = rc.Top + 20;
  rc.Left = rc.Left + 20;
  rc.Bottom = rc.Bottom - 20;
  rc.Right = rc.Right - 20;

 

   
4
 
Drawing the Image    
     

The default size of the Canvas is the natural, un-cropped size of the first image drawn on it. We are going to crop the image so we have to manually set the Canvas size to take this into account. We also use the Pos parameter to shift the image up and left to cater for our border width.

[Visual Basic]
  ca.Height = rc.Height
  ca.Width = rc.Width
  ca.DrawFile(inpath, "Pos=-20,-20 SrcRect=" + rc.String)

[C#]
  ca.Height = rc.Height;
  ca.Width = rc.Width;
  ca.DrawFile(inpath, "Pos=-20,-20 SrcRect=" + rc.String);

 

   
5
 
Saving    
     

Finally we save the picture as a JPEG image.

[Visual Basic]
  ca.SaveAs(outpath , "")
End If

[C#]
  ca.SaveAs(outpath , "");
}

 

   
6
 
Input and Output    
     

Sample input and output images are shown below.

birds.jpg

croppedbirds.jpg