Ian Devlin
Ian Devlin

Reputation: 18870

Creating new image from cropped image

I'm currently trying to crop an image, and then save the new image. I have the original image, the x and y co-ordinates of where on that image I want the cropping to being, and the width and height of the new cropped image.

Here is my code:

Bitmap originalBitmap = new Bitmap(filePath);
Bitmap newImage = new Bitmap(width, height);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(originalBitmap, x, y, width, height);
newImage.Save(newFilePath);

But when the image is acutally saved, it's a small image of the correct height and width, but is completely empty.

I'm sure I'm just missing a trick here, or completely misunderstanding something (or both!), so any help at all would be appreciated!

Upvotes: 3

Views: 347

Answers (1)

manji
manji

Reputation: 47968

try using Clone function of Bitmap:

Bitmap newImage = originalBitmap.Clone(new RectangleF(x, y, width, height),  
                                       System.Drawing.Imaging.PixelFormat.Format32bppArgb);
newImage.Save(newFilePath);

Upvotes: 3

Related Questions