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

霸气de小男生 提交于 2019-12-06 11:20:11

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.

Kirsten Greed

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;
}

You can do:

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