3
Answers

Improper results while cropping in picturebox- C#

Arun E

Arun E

8y
231
1
Hello experts,
Basically i will be importing images to a picturebox from folders(say 20 images) using selection through combobox.When i try to crop those imported images the result is improper i.e,the cropped area of the image is not the selected part and also it is zoomed to a greater extent. I am working in Visual Studio 2013 with c# Windowsfrom. Thanks in advance.
This is the code i tried with,

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{
private Image _originalImage;
private bool _selecting;
private Rectangle _selection;
Boolean bHaveMouse;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)

{

 if (e.Button == MouseButtons.Left) {             _selecting = true;             _selection = new Rectangle(new Point(e.X, e.Y), new Size()); } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) {           bHaveMouse = true;           ptOriginal.X = e.X;         ptOriginal.Y = e.Y; if (e.Button == MouseButtons.Left && _selecting) { Image img = pictureBox1.Image.Crop(_selection);               pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;             pictureBox1.Image = img.Fit2PictureBox(pictureBox1);             _selecting = false; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (_selecting) {             _selection.Width = e.X - _selection.X;             _selection.Height = e.Y - _selection.Y;               pictureBox1.Refresh(); } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (_selecting) { Pen pen = Pens.GreenYellow;             e.Graphics.DrawRectangle(pen, _selection); } }

public static Image Crop(this Image image, Rectangle selection) { Bitmap bmp = image as Bitmap;

 if (bmp == null) throw new ArgumentException("Kein gültiges Bild (Bitmap)"); Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat);           image.Dispose(); return cropBmp; } public static Image Fit2PictureBox( this Image image, PictureBox picBox) { Bitmap bmp = null; Graphics g; double scaleY = (double)image.Width / picBox.Width; double scaleX = (double)image.Height / picBox.Height; double scale = scaleY < scaleX ? scaleX : scaleY;           bmp = new Bitmap( (int)((double)image.Width / scale), (int)((double)image.Height / scale));           bmp.SetResolution(             image.HorizontalResolution,             image.VerticalResolution);           g = Graphics.FromImage(bmp);            g.DrawImage(             image, new Rectangle( 0, 0,                 bmp.Width, bmp.Height), new Rectangle( 0, 0,                 image.Width, image.Height), GraphicsUnit.Pixel);         picBox.SizeMode = PictureBoxSizeMode.StretchImage;           g.Dispose();           image.Dispose(); return bmp; } }

}

 
Answers (3)