Cropping an image

P

Paul E Collins

I need to load a bitmap image, crop it, and save it.

By cropping, I don't mean resizing - I mean reducing it to a fixed size
area.

Image img = Bitmap.FromFile("in.bmp");
// what goes here?
img.Save("out.bmp");
img.Dispose();

Code rather than a URL would be ideal, as VB.NET examples do nothing for me.

Thanks.

P.
 
N

Nicholas Paldino [.NET/C# MVP]

Paul,

What you need to do is create a new instance of the Bitmap class which
starts out as the size that you want to crop down to.

Then, pass the instance of the new image to the static FromImage method
on the Graphics class. This will return a Graphics instance you can use to
draw the cropped image on.

Once you have that, you can call the following overload of DrawImage:

Overloads Public Sub DrawImage( _
ByVal image As Image, _
ByVal destPoints() As Point, _
ByVal srcRect As Rectangle, _
ByVal srcUnit As GraphicsUnit _
)

This will allow you to pass the original Image instance, as well as the
area on it you want to paint, as well as the destination area.

Hope this helps.
 
P

Paul E Collins

Nicholas Paldino said:
What you need to do is create a new instance of
the Bitmap class which starts out as the size that
you want to crop down to.
Then, pass the instance of the new image to the
static FromImage method on the Graphics class.
This will return a Graphics instance you can use to
draw the cropped image on.
Once you have that, you can call the following
overload of DrawImage: [...]

Thanks.

However, unlike Image, Graphics doesn't seem to have a method that saves to
a file. Having drawn what I want onto the Graphics object, how can I save
the result?

P.
 
N

Nicholas Paldino [.NET/C# MVP]

Paul,

Ahh, you don't have to do anything. The Graphics instance that you drew
into is the Graphics context for the new bitmap you created! Once you are
done drawing (and properly disposing of the graphics object), you can just
call the Save method on the Bitmap/Image instance and save it wherever you
wish.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Paul E Collins said:
Nicholas Paldino said:
What you need to do is create a new instance of
the Bitmap class which starts out as the size that
you want to crop down to.
Then, pass the instance of the new image to the
static FromImage method on the Graphics class.
This will return a Graphics instance you can use to
draw the cropped image on.
Once you have that, you can call the following
overload of DrawImage: [...]

Thanks.

However, unlike Image, Graphics doesn't seem to have a method that saves to
a file. Having drawn what I want onto the Graphics object, how can I save
the result?

P.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top