裁剪图像到4:3宽高比c#

Chr*_*son 1 c# graphics gdi crop drawimage

我正在艰难地围绕如何计算出裁剪任何高宽比超过4:3到4:3的图像的数学.

例如,我可能有一些16:9的图像,我希望调整大小然后裁剪为4:3.

调整大小我已经工作了,但它保持相同的宽高比.我知道我需要使用Graphics.DrawImage()但是我不完全确定参数应该是什么以及我如何得出这些参数.

这就是我所知道的:

var dimension = (double)bigSide/smallSide
if(dimension > 1.4)
{
  Graphics.DrawImage(resImage, new Rectangle(?, ?, ?, ?), ?, ?, ?, ?, GraphicsUnit.Pixel);
}
Run Code Online (Sandbox Code Playgroud)

所有这些问号都是我不理解的参数.我也不确定将图像缩小到4:3需要什么样的数学运算.

基本上我只是希望切割比4:3宽度更宽的图像(中心).显然,我会剪切图像的顶部和底部,而不是横向.

任何帮助将不胜感激.

TIA

Say*_*yka 6

我看到你评论说你想要将裁剪后的图像调整到更小的尺寸吗?

Image resizeImg(Image img, int width)
    {
        // 4:3 Aspect Ratio. You can also add it as parameters
        double aspectRatio_X = 4;
        double aspectRatio_Y = 3;                        
        double targetHeight = Convert.ToDouble(width) / (aspectRatio_X / aspectRatio_Y);

        img = cropImg(img);
        Bitmap bmp = new Bitmap(width, (int)targetHeight);
        Graphics grp = Graphics.FromImage(bmp);
        grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
        return (Image)bmp;

    }

    Image cropImg(Image img)
    {
        // 4:3 Aspect Ratio. You can also add it as parameters
        double aspectRatio_X = 4;
        double aspectRatio_Y = 3;

        double imgWidth = Convert.ToDouble(img.Width);
        double imgHeight = Convert.ToDouble(img.Height);

        if (imgWidth / imgHeight > (aspectRatio_X / aspectRatio_Y))
        {
            double extraWidth = imgWidth - (imgHeight * (aspectRatio_X / aspectRatio_Y));
            double cropStartFrom = extraWidth / 2;
            Bitmap bmp = new Bitmap((int)(img.Width - extraWidth), img.Height);
            Graphics grp = Graphics.FromImage(bmp);                                                
            grp.DrawImage(img, new Rectangle(0, 0, (int)(img.Width - extraWidth), img.Height), new Rectangle((int)cropStartFrom, 0, (int)(imgWidth - extraWidth), img.Height), GraphicsUnit.Pixel);
            return (Image)bmp;
        }
        else
            return null;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox2.Image = resizeImg(pictureBox1.Image, 60);
    }
Run Code Online (Sandbox Code Playgroud)

使用resize方法并提供width作为参数.无需添加高度,因为它是通过裁剪方法完成的.