获取Picturebox内缩放图像的精确大小

时间:2015-12-31 21:38:22

标签: c# .net image winforms picturebox

我正在使用WinForms。在我的表格中,我有一个picturebox。它的sizemode设置为Zoom。如果我将图片加载到picturebox,则图片会根据picturebox尺寸进行缩放。

我想知道如何在picturebox内获得缩放图像的大小。

这些是我尝试过的一些东西,但这并没有给我我想要的结果。

    private void Debug_Write_Click(object sender, EventArgs e)
    {
        //var pictureWidth = pictureBox1.ClientSize.Width; //This gives the size of the picturebox
        //var picturewidth1 = pictureBox1.Image.Width; This gives the actual size of the image


        //var pictureHight = pictureBox1.ClientSize.Height; //This gives the size of the picturebox
        //var pictureHight1 = pictureBox1.ClientSize.Height; This gives the actual size of the image

        Debug.WriteLine("Width: " + pictureWidth.ToString() + " Height: " + pictureHight.ToString());
    }

实施例: 图像的实际尺寸enter image description here

Picturebox尺寸模式设置为Zoom,因此根据我的picturebox尺寸缩放图片:

enter image description here

如何找出此图像的缩放长度和宽度?

1 个答案:

答案 0 :(得分:6)

你应该做数学!

Image img = //...;
PictureBox pb = //...;

var wfactor = (double)img.Width / pb.ClientSize.Width;
var hfactor = (double)img.Height / pb.ClientSize.Height;

var resizeFactor = Math.Max(wfactor, hfactor);
var imageSize = new Size((int)(img.Width / resizeFactor), (int)(img.Height / resizeFactor));