使图像适合PictureBox [英] Fit Image into PictureBox

查看:112
本文介绍了使图像适合PictureBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
    myDatabaseConnection.Open();
    using (SqlCommand SqlCommand = new SqlCommand("Select Photo from Employee where EmpID LIKE '%' + @EmpID + '%' ", myDatabaseConnection))
    {
        SqlCommand.Parameters.AddWithValue("@EmpID", textBox1.Text);
        DataSet DS = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(SqlCommand);
        adapter.Fill(DS, "Images");

        var imagesTable = DS.Tables["Images"];
        var imagesRows = imagesTable.Rows;
        var count = imagesRows.Count;

        if (count <= 0)
            return;
        var imageColumnValue =
            imagesRows[count - 1]["Image"];
        if (imageColumnValue == DBNull.Value)
            return;

        var data = (Byte[])imageColumnValue;
        using (var stream = new MemoryStream(data))
        {
            pictureBox1.Image = Image.FromStream(stream);
        }

    }
}

如果图片太大,无法容纳图片框。使图像适合图片框的代码是什么?
我的图片框是平方的,如果图像是矩形的,如何裁剪并将其显示在图片框中,如这个,图片的下半部分将被删除。

If the image is too large for the picturebox to fit. What is the code to make the image fit in the picturebox? My picturebox is squared, if the image is rectangular how to it crop and show it in the picturebox like this, the lower part of the picture will be removed.

推荐答案

首先,为了让任何图像调整大小以适合图片框,你可以设置 PictureBox.SizeMode = PictureBoxSizeMode.StretchImage

First off, in order to have any image "resize" to fit a picturebox, you can set the PictureBox.SizeMode = PictureBoxSizeMode.StretchImage

如果你想事先裁剪图像(即切掉边或顶部和底部),那么你需要清楚地定义你想要的行为(从顶部开始) ,填充pciturebox的高度并裁剪其余部分,或者从底部开始,将图片框的高度填充到顶部等,并且使用图片框和图片框的高度/宽度属性应该相当简单图像剪辑图像并获得您正在寻找的效果。

If you want to do clipping of the image beforehand (i.e. cut off sides or top and bottom), then you need to clearly define what behavior you want (start at top, fill the height of the pciturebox and crop the rest, or start at the bottom, fill the height of the picturebox to the top, etc), and it should be fairly simple to use the Height / Width properties of both the picturebox and the image to clip the image and get the effect you are looking for.

这篇关于使图像适合PictureBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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