Select Area of Image

余生长醉 提交于 2019-12-24 17:43:30

问题


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);
}

回答1:


In order to select the correct section, just replace:

g3.DrawImageUnscaled(origImage, 0, 0, 16, 16);

with

g3.DrawImageUnscaled(origImage, -5, -5, 16, 16);



回答2:


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



来源:https://stackoverflow.com/questions/14537669/select-area-of-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!