且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

图像数据绑定到pictureBox

更新时间:2023-10-14 11:34:04

解决方案可以很简单这样:

The solution can be as simple as this:

imgusr.DataBindings.Add(new Binding("Image", data_set, 
                                    "yourtablename.yourcolumnname", true));

请注意,您需要告知 Binding 通过将最后一个参数( enableFormatting )设置为 true 来进行格式化

Note that you need to tell the Binding to do the formatting by setting the last parameter (enableFormatting) to true. No more special code is needed to process the image.

还要注意,我没有尝试必要的格式以在列名中使用空格和撇号。我建议使用标准名称!

Also note that I didn't try the necessary formatting to use blanks and apostrophes in the column name. I recommend using standard names!

最后确保设置 TableName 属性>要在数据集中中使用的表:

And finally make sure to set the TableName property of the Table you want to use in your DataSet:

data_set.Tables[0].TableName = "yourtablename";

更新,您似乎没有保存图像数据正确地连接到您的dbms。这是您的例程的一个版本,应该会更好地工作:

Update from your discussion it seems that you do not save the image data correctly to your dbms. Here is a version of your routine, that should work better:

byte[] img_byte = null;
long imgfilelength = 0;

private void StoreImage(string ChosenFile)
{
    try { 
        using (Image img = Image.FromFile(ChosenFile))
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Close();
            img_byte = ms.ToArray();
            imgfilelength = img_byte.Length;
        }
    } catch (Exception e) { MessageBox.Show(e.ToString()); }
}

测试是如此简单:

private void test_button_Click(object sender, EventArgs e)
{
    StoreImage(someImageFile);
    using (MemoryStream ms = new MemoryStream(img_byte))
    {
        aPictureBox.Image = Image.FromStream(ms);
    }
}

请确保使用正确的文件格式,例如 Png Jpeg 等。

Do make sure to use the correct file format, e.g. Png or Jpeg etc..