当前位置:网站首页> 体育知识 > 怎么把图片存到数据库中(C#如何将数据库的二进制图片显示出来)

怎么把图片存到数据库中(C#如何将数据库的二进制图片显示出来)

更新时间:2022-10-02 10:49:03

将图片以二进制流的方式存到数据库后,在进行查询或者修改的时候需要展示出来,下面介绍一种展示方式。

一、查询方法

/// <summary>
/// 获取图片二进制流
/// </summary>
/// <param name="CmdText"></param>
/// <param name="filed"></param>
/// <returns></returns>
public Image GetImageBySql(string CmdText, String filed)
{
  //_Connect是链接数据库的字符串
    SqlConnection SqlCon = _Connect;
    SqlCommand cmd = new SqlCommand();

    try
    {
        if (SqlCon != null && SqlCon.State != ConnectionState.Open)
        {
            SqlCon.Open();
        }
        cmd.Connection = SqlCon;
        cmd.CommandText = CmdText;
        SqlDataReader sdr = cmd.ExecuteReader();
        byte[] bytFile;
        if (sdr.Read())
        {
            bytFile = (Byte[])sdr[filed];
        }
        else
        {
            bytFile = new byte[0];
            return null;
        }
        sdr.Close();
        MemoryStream ms = new MemoryStream(bytFile, 0, bytFile.Length);
        return Image.FromStream(ms);
    }
    catch (Exception ex)
    {
        return null;
    }
    finally
    {
        if (SqlCon != null && SqlCon.State != ConnectionState.Closed)
        {
            SqlCon.Close();
        }
    }
}

二、调用查询并展示

string sql ="xxxxxxx";//查询出img字段的值 ,数据库该字段的类型为image
//img是图片字段名或者别名
if (DataAccess.Access().GetImageBySql(sql, "img") != null)
{
    this.pictureBox1.Image = DataAccess12.Access().GetImageBySql(sql, "img");
    Bitmap bmPic = new Bitmap(DataAccess12.Access().GetImageBySql(sql, "img"));
    Point ptLoction = new Point(bmPic.Size);
  //下面语句是让图片自适应pictureBox1控件
    if (ptLoction.X > pictureBox1.Size.Width || ptLoction.Y > pictureBox1.Size.Height)
    {
        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
    }
    else
    {
        pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
    }
}
else
{
    this.pictureBox1.Image = null;
}