Windows Forms: How to directly bind a Bitmap to a PictureBox?

江枫思渺然 提交于 2019-12-08 01:41:21

问题


I'm just trying to build a small C# .Net 4.0 application using Windows Forms (WPF I don't know at all, Windows Forms at least a little :-) ).

Is it possible to directly bind a System.Drawing.Bitmap object to the Image property of a PictureBox? I tried to use PictureBox.DataBindings.Add(...) but this doesn't seem to work.

How can I do this?

Thanks and best regards,
Oliver


回答1:


This works for me:

Bitmap bitmapFromFile = new Bitmap("C:\\temp\\test.bmp");

pictureBox1.Image = bitmapFromFile;

or, in one line:

pictureBox1.Image = new Bitmap("C:\\temp\\test.bmp");

You might be overcomplicating this - according to the MSDN documentation, you can simple assign the bitmap directly to the PictureBox.Image property.




回答2:


You can use the PictureBox.DataBindings.Add(...)
The trick is to create a separate property on the object you are binding to to handle the conversion between null and and empty picture.

I did it this way.

In my form load I used

this.PictureBox.DataBindings.Add(new Binding("Visible", this.bindingSource1, "HasPhoto", false, DataSourceUpdateMode.OnPropertyChanged));

this.PictureBox.DataBindings.Add(new Binding("Image", this.bindingSource1, "MyPhoto",false, DataSourceUpdateMode.OnPropertyChanged));

In my object I have the following

[NotMapped]
public System.Drawing.Image MyPhoto
{
    get
    {            
        if (Photo == null)
        {
           return BlankImage;        
        }
        else
        {
           if (Photo.Length == 0)
           {
              return BlankImage;     
           }
           else
           {
              return byteArrayToImage(Photo);
           }
        }
    }
    set
    {
       if (value == null)
       {
          Photo = null;
       }
       else
       {
           if (value.Height == BlankImage.Height)  // cheating
           {
               Photo = null;
           }
           else
           {
               Photo = imageToByteArray(value);
           }
        }
    }
}

[NotMapped]
public Image BlankImage {
    get
    {
        return new Bitmap(1,1);
    }
}

public static byte[] imageToByteArray(Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms, ImageFormat.Gif);
    return ms.ToArray();     
}

public static Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}



回答3:


You can do:

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourfile.bmp");
picturebox1.Image = bmp;


来源:https://stackoverflow.com/questions/11283212/windows-forms-how-to-directly-bind-a-bitmap-to-a-picturebox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!