C#中如何从数据库中获取图片

How to retrieve image from database in c#

一个错误显示说我有这个代码的无效参数... 谁能告诉我怎么了?我应该获取分配给 clientID 的图像。

private void button1_Click(object sender, EventArgs e)
{
        MySqlConnection conn = new MySqlConnection(mycon);
        MySqlCommand cmd = new MySqlCommand("SELECT clientImage FROM client WHERE clientID='" + label2.Text + "'", conn);

        conn.Open();
        MySqlDataReader myReader = null;
        myReader = cmd.ExecuteReader();

        while (myReader.Read())
        {
            byte[] imgg = (byte[])(myReader["clientImage"]);
            if (imgg == null)
            {
                pictureBox1.Image = null;
            }
            else
            {
                MemoryStream mstream = new MemoryStream(imgg);
                pictureBox1.Image = System.Drawing.Image.FromStream(mstream);
            }
        }
        conn.Close();
}

这段代码可能会派上用场。我试过了

byte[] imagedata = (byte [])dataGridView1[4, dataGridView1.SelectedRows[0].Index].Value;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(imagedata, 0, imagedata.Length))
            {
                ms.Write(imagedata, 0, imagedata.Length);
                //Set image variable value using memory stream.
                image = Image.FromStream(ms, true );
            }

此代码有效。 MySql 沼泽。

using System.IO;

string appPath = Path.GetDirectoryName(Application.Executable) + @"/student Images/";
string imagename;

//put this code below to load form.
getimage();
if(File.Exist(appPath + imagename)
{
PictureBox1.Image = Image.FromFile(appPath + imagename);
}
else
{
PictureBox1.Image = Properties.Resources.Image_notfound;
}

private void getimage()
{
MySqlConnection connect = new MySqlConnection(con);
MySqlCommand cmd = new MySqlCommand("SELECT PictureName as 'pic' FROM userprofile where ID='" + datagrid.CurrentRow.Cells["ID"].ToString() + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
Try
{
MySqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
imagename = dr.GetString("pic");
}
dr.Close();
}
catch(Exception ee)
{
Console.WriteLine(ee.ToString());
}
finally
{
connect.Close();
}

控制器

using System.IO;

using (TESTDBEntities db = new TESTDBEntities())
{
   // first create var 
    var item = (from d in db.Hunger_tbl_MainCategory select d).ToList();
    return View(item); // your view
}

查看

@model List<WebApplication1.Models.TEST_tbl_IMG`enter code here`>

@foreach (var item in Model)
{
    <div class="cards-list">
        <div class="card 1">
            @{ 
                var base64 = Convert.ToBase64String(item.CategoryImage);
                var imgsrc = string.Format("data:image/png;base64,{0}", base64);
            }
            <div class="card_image"> <img src='@imgsrc'/></div>
        </div>
    </div>
}