Search code examples
c#imagebitmapcrop

How to Set my X and Y Of Pic To save an image C#


I Have A Pic For Example ( This Pic Have a X:467 Y:300 ) I Just Need From X:0 Y:0 To X:200 Y:45 I Use This Code For Crop But I Lost Data Of X:0 Y:0 To X:200 Y:45 I Don't Know What To Do

bmp.Save("@image.png", ImageFormat.Png);
        Image img = new Bitmap("@image.png");
        Rectangle source = new Rectangle(0, 0, ww, hh);
        Image cropped = CropImage(img, source);
        cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));
    }

    private Bitmap CropImage(Image originalImage, Rectangle sourceRectangle,Rectangle? destinationRectangle = null)
    {
        if (destinationRectangle == null)
        {
            destinationRectangle = new Rectangle(Point.Empty, sourceRectangle.Size);
        }

        var croppedImage = new Bitmap(destinationRectangle.Value.Width,
            destinationRectangle.Value.Height);
        using (var graphics = Graphics.FromImage(croppedImage))
        {
            graphics.DrawImage(originalImage, destinationRectangle.Value,
                sourceRectangle, GraphicsUnit.Pixel);
        }
        return croppedImage;
    }

Solution

  • From the comments I understand that you want to crop the image before saving the original image to disk. In that case you can directly supply the image to the crop method:

        // bmp.Save("@image.png", ImageFormat.Png);
        // Image img = new Bitmap("@image.png");
        Rectangle source = new Rectangle(0, 0, ww, hh);
        Image cropped = CropImage(bmp, source); // <-- bmp supplied to crop method directly
        cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));