Reputation: 397
I'm trying to select an area of an image I've selected using openfiledialog The area I'm trying to select is 16x16 from x,y coordinates 5,5 Once selected I want to draw the 16x16 image into another pictureBox at coordinates 0,0
This is the code I've got but I can't get it to select the correct part of the original image, anybody any suggestions as to why it doesn't work?
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
Image origImage = Image.FromFile(openFileDialog1.FileName);
pictureBoxSkin.Image = origImage;
lblOriginalFilename.Text = openFileDialog1.SafeFileName;
System.Drawing.Bitmap bmp = new Bitmap(16, 16);
Graphics g3 = Graphics.FromImage(bmp);
g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);
Graphics g2 = pictureBoxNew.CreateGraphics();
g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);
}
Upvotes: 1
Views: 4192
Reputation: 32551
In order to select the correct section, just replace:
g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);
with
g3.DrawImageUnscaled(origImage, -5, -5, 16, 16);
Upvotes: 2
Reputation: 18443
replace this:
Graphics g2 = pictureBoxNew.CreateGraphics();
g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);
with this:
pictureBoxNew.Image = bmp;
and you're fine.
Complete code:
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
Image origImage = Image.FromFile(openFileDialog1.FileName);
pictureBoxSkin.Image = origImage;
lblOriginalFilename.Text = openFileDialog1.SafeFileName;
System.Drawing.Bitmap bmp = new Bitmap(16, 16);
Graphics g3 = Graphics.FromImage(bmp);
g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);
pictureBoxNew.Image = bmp;
//Graphics g2 = pictureBoxNew.CreateGraphics();
//g2.DrawImageUnscaled(bmp, 0, 0, 16, 16);
}
When you draw something anywhere outside a Paint
event, it will erased as soon as the control need to be painted again (ie. when restored from minimized state, another window passes over your window, or you call the Refresh
method). So, put the drawing code for controls inside their Paint
event, or let the control manage the painting of your image (in this case, assigning an Image
to the PictureBox
control).
Upvotes: 0