namespace WindowsFormsApplication1
{
public partial class Form1 : Form
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; } }
}