如何将图像加载到PictureBox;基于存储在DataBase中的图像位置

时间:2014-07-28 06:37:36

标签: c# sql winforms picturebox

我有sql数据库,我将图像保存为图像位置

例如

D:\Local Pictures\Users\XXXX_XXXX_1.jpg

我正在尝试使用此代码将其放在图片框中

DataConnection myCon = new DataConnection(); // Contains Data Connection String
SqlConnection con1 = new SqlConnection(@"Data Source=.\SQLS2012;Initial Catalog=test;Integrated Security=True");
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT * From USER_TABLE WHERE USERID =" + userIdTextBox.Text,con1);

myReader = myCommand.ExecuteReader();

while (myReader.Read())
{
    nameTextBox.Text = (myReader["FIRST_NAME"].ToString());
    lnameTextBox.Text = (myReader["LAST_NAME"].ToString());
    posTextBox.Text = (myReader["POSITION"].ToString());
    emailTextBox.Text = (myReader["E_MAIL"].ToString());
    phoneTextBox.Text = (myReader["PHONE"].ToString());
    usernameTextBox.Text = (myReader["USERNAME"].ToString());
    userLevelTextBox.Text = (myReader["USER_LEVEL"].ToString());
    string filename = (myReader["PROFILE_PICTURE"].ToString());
    profilePicBox.ImageLocation = filename;

}

当我执行此代码时,我在图像中获得小x图像白色背景。如何修复和加载图像

2 个答案:

答案 0 :(得分:2)

<强>装载

MSDN对此问题并不完全清楚 - ImageLocation property,但似乎设置ImageLocation属性可能无法正确加载图片,因此您可能会尝试使用{{3}而不是方法:

...
string filename = (myReader["PROFILE_PICTURE"].ToString());
profilePicBox.Load(filename);

修改

ImageLocation应该可以正常工作,只需确保路径正确并且不使用相对路径 - PictureBox.Load

定位和尺寸:

并确保与尺寸和位置相关的How do I put an image into my picturebox using ImageLocation?可以处理不同的图像尺寸。

答案 1 :(得分:0)

在while循环中进行此更改

        while (myReader.Read())
        {
            nameTextBox.Text = (myReader["FIRST_NAME"].ToString());
            lnameTextBox.Text = (myReader["LAST_NAME"].ToString());
            posTextBox.Text = (myReader["POSITION"].ToString());
            emailTextBox.Text = (myReader["E_MAIL"].ToString());
            phoneTextBox.Text = (myReader["PHONE"].ToString());
            usernameTextBox.Text = (myReader["USERNAME"].ToString());
            userLevelTextBox.Text = (myReader["USER_LEVEL"].ToString());
            string filename = (myReader["PROFILE_PICTURE"].ToString());
            profilePicBox.Image = Image.FromFile(filename )

        }