noobS41bot
noobS41bot

Reputation: 71

Cropping Images .Net

I am trying to do a simple crop of an image, but for some reason it is not respecting my starting x,y location. It is always starting the crop at 0,0. The following is what I am doing:

Bitmap original = new Bitmap(pictureBox1.Image);

        int x = Convert.ToInt32(txtX.Text);
        int y = Convert.ToInt32(txtY.Text);
        int dX = Convert.ToInt32(txtDeltaX.Text);
        int dY = Convert.ToInt32(txtDeltaY.Text);

        Point loc = new Point(x, y);
        Size cropSize = new Size(dX, dY);

        Rectangle cropArea = new Rectangle(loc, cropSize);

        Bitmap bmpCrop = CropImage(original, cropArea);

        pictureBox1.Image = bmpCrop;

The cropping method:

public Bitmap CropImage(Bitmap source, Rectangle section)
    {
        // An empty bitmap which will hold the cropped image  
        Bitmap bmp = new Bitmap(section.Width, section.Height);
        Graphics g = Graphics.FromImage(bmp);
        // Draw the given area (section) of the source image  
        // at location 0,0 on the empty bitmap (bmp)  
        g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
        return bmp;
    }  

This should be very simple, but for some reason its not working. Its cropping it, just at 0,0.

Thanks!

Upvotes: 2

Views: 5301

Answers (3)

Yahia
Yahia

Reputation: 70369

You might want to use Graphics.DrawImageUnscaledAndClipped

Upvotes: 1

Tigran
Tigran

Reputation: 62248

Try to use, something like this :

g.DrawImage(source, x, y, section, GraphicsUnit.Pixel);

Upvotes: 0

Marco
Marco

Reputation: 57573

You should try to use

g.DrawImage(source, section);

Anyway this function works:

public Bitmap CropBitmap(Bitmap bitmap, 
                         int cropX, int cropY, 
                         int cropWidth, int cropHeight)
{
    Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
    Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
    return cropped;
}

Upvotes: 5

Related Questions