How to crop an image in vb.net?

后端 未结 3 2059
抹茶落季
抹茶落季 2021-01-18 02:17

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

3条回答
  •  抹茶落季
    2021-01-18 02:24

    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..

提交回复
热议问题