I am unable to crop an image in a picturebox in strechmode which i tried for weeks and dint get a solution yet. The problem is my images size is say(1200,750) and the picture size is say(450,300) but when i try to crop it in picturebox in strechmode it takes the coordinates of original size of the image(1200,750) but i need to crop with the coordinates of the image displayed in picturebox(450,300), therefore i am getting faulty results in cropping. I am working with visual studio 2013 in c# winforms. Please provide me with a solution. Thank you in advance.
What I have tried:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
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_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;
}
button5.Enabled = true;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (_selecting)
{
Pen pen = Pens.GreenYellow;
e.Graphics.DrawRectangle(pen, _selection);
}
}
the namespace class i used is as followsnamespace gfoidl.Imaging {
public static class ImageExtension
{
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;
}
}
}` invoked it in the main program with the header using gfoid1.imaging;