Search code examples
vb.netimagecrop

How to crop an image in vb.net?


The image can be anything. It can be jpg, png, anything.

Load it.

Crop it. Say removing first 100 pixels from the left.

Save to the same file


Solution

  • Use Graphics.DrawImage Method (Image, RectangleF, RectangleF, GraphicsUnit) method.

        Dim fileName = "C:\file.jpg"
        Dim CropRect As New Rectangle(100, 0, 100, 100)
        Dim OriginalImage = Image.FromFile(fileName)
        Dim CropImage = New Bitmap(CropRect.Width, CropRect.Height)
        Using grp = Graphics.FromImage(CropImage)
            grp.DrawImage(OriginalImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
            OriginalImage.Dispose()
            CropImage.Save(fileName)
        End Using