如何在以拉伸模式显示图像的pictureBox中裁剪原始图像? [英] How can I crop original image in a pictureBox that shows image in Stretch mode?

查看:104
本文介绍了如何在以拉伸模式显示图像的pictureBox中裁剪原始图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I crop an image in a pictureBox that shows in Stretch mode?

我在pictureBox中绘制一个矩形:

I draw a rectangle in 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中绘制的矩形大小的原始图像?

but the quality of the cropped image is very low because it cropped the stretch Image not the original image. How can I crop the original image with size of rectangle that User drawing in pictureBox?

推荐答案

我将pictureBox1_MouseUp代码更改为:

I changed pictureBox1_MouseUp code to :

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

而且有效.感谢汉斯·帕桑特"的回答.

And it's worked. Thanks to 'Hans Passant' for his answer.

这篇关于如何在以拉伸模式显示图像的pictureBox中裁剪原始图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆