Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crop an image in vb.net?

Tags:

image

vb.net

crop

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

like image 357
user4951 Avatar asked Jan 04 '12 10:01

user4951


2 Answers

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
like image 52
KV Prajapati Avatar answered Oct 01 '22 18:10

KV Prajapati


Ref: Graphics.DrawImage and Image Cropping with Image Resizing Using VB.NET

private void btnCropImage_Click(object sender, EventArgs e)
    {
        OpenFileDialog dlg = new OpenFileDialog();
        dlg.ShowDialog();
        //check your filename or set constraint on fileopen dialog
        //to open image files
        string str = dlg.FileName;

        //Load Image File to Image Class Object to make crop operation
        Image img = System.Drawing.Bitmap.FromFile(str);

        // Create rectangle for source image, what ever it's size. 
        GraphicsUnit units = GraphicsUnit.Pixel;
        RectangleF srcRect = img.GetBounds(ref units);

        // Create rectangle for displaying image - leaving 100 pixels from left saving image size.
        RectangleF destRect = new RectangleF(100.0F, 0.0F, srcRect.Width - 100, srcRect.Height);

        // Bitmap class object to which saves croped image
        Bitmap bmp = new Bitmap((int)srcRect.Width - 100, (int)srcRect.Height);

        // Draw image to screen.
        Graphics grp = Graphics.FromImage(bmp);
        grp.DrawImage(img, destRect, srcRect, units);

        //save image to disk
        bmp.Save("e:\\img.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);

        //Clear memory for Unused Source Image
        img.Dispose();
    }

Hope this help you..

like image 42
Niranjan Singh Avatar answered Oct 01 '22 17:10

Niranjan Singh