如何在以拉伸模式显示图像的pictureBox中裁剪原始图像?

时间:2013-11-25 13:14:06

标签: c# image bitmap crop picturebox

如何在Stretch模式下显示的pictureBox中裁剪图像?

我在pictureBox中绘制一个矩形:

void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {

        //pictureBox1.Image.Clone();
        xUp = e.X;
        yUp = e.Y;
        Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
        using (Pen pen = new Pen(Color.YellowGreen, 3))
        {

            pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
        }
        rectCropArea = rec;
    }

    void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        pictureBox1.Invalidate();

        xDown = e.X;
        yDown = e.Y;
    }

并使用以下方式裁剪所选部分:

private void btnCrop_Click(object sender, EventArgs e)
    {
        try
        {
            pictureBox3.Refresh();
            //Prepare a new Bitmap on which the cropped image will be drawn
            Bitmap sourceBitmap = new Bitmap(pictureBox1.Image, pictureBox1.Width, pictureBox1.Height);
            Graphics g = pictureBox3.CreateGraphics();

            //Draw the image on the Graphics object with the new dimesions
            g.DrawImage(sourceBitmap, new Rectangle(0, 0, pictureBox3.Width, pictureBox3.Height), rectCropArea, GraphicsUnit.Pixel);
            sourceBitmap.Dispose();
        }
        catch (Exception ex)
        {

        }
    }

但裁剪图像的质量非常低,因为裁剪后的图像不是原始图像。如何裁剪原始图像的大小为用户在pictureBox中绘制的矩形?

1 个答案:

答案 0 :(得分:5)

我将pictureBox1_MouseUp代码更改为:

void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
            xUp = e.X;
            yUp = e.Y;

            Rectangle rec = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));

            using (Pen pen = new Pen(Color.YellowGreen, 3))
            {

                pictureBox1.CreateGraphics().DrawRectangle(pen, rec);
            }

            xDown = xDown * pictureBox1.Image.Width / pictureBox1.Width;
            yDown = yDown * pictureBox1.Image.Height / pictureBox1.Height;

            xUp = xUp * pictureBox1.Image.Width / pictureBox1.Width;
            yUp = yUp * pictureBox1.Image.Height / pictureBox1.Height;

            rectCropArea = new Rectangle(xDown, yDown, Math.Abs(xUp - xDown), Math.Abs(yUp - yDown));
    }

它有效。感谢'Hans Passant'的回答。