c#form+mysql储存读取图片_C# 图片保存到数据库和从数据库读取图片并显示

图片保存到数据库的方法:

public void imgToDB(string sql)

{   //参数sql中要求保存的imge变量名称为@images

//调用方法如:imgToDB("update UserPhoto set Photo=@images where UserNo='" + temp + "'");

FileStream fs = File.OpenRead(t_photo.Text);

byte[] imageb = new byte[fs.Length];

fs.Read(imageb, 0, imageb.Length);

fs.Close();

SqlCommand com3 = new SqlCommand (sql,con);

com3.Parameters.Add("@images", SqlDbType.Image).Value = imageb;

if (com3.Connection.State == ConnectionState.Closed)

com3.Connection.Open();

try

{

com3.ExecuteNonQuery();

}

catch

{ }

finally

{ com3.Connection.Close(); }

}

数据库中读出图片并显示在picturebox中:

方法一:

private void ShowImage(string sql)

{

//调用方法如:ShowImage("select Photo from UserPhoto where UserNo='" + userno +"'");

SqlCommand cmd = new SqlCommand(sql, conn);

conn.Open();

byte[] b= (byte[])cmd.ExecuteScalar();

if (b.Length 〉 0)

{

MemoryStream stream = new MemoryStream(b, true);

stream.Write(b, 0, b.Length);

pictureBox1.Image =

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解决这个问题。 首先,让我们来看一下如何将图片保存数据库中。假设你有一个名为`image`的`byte[]`数组,它包含了你要保存图片数据。以下是一个例子,用于将这个数组保存到 SQL Server 数据库中的一个名为`image_table`的表中: ```csharp using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "INSERT INTO image_table (image_data) VALUES (@ImageData)"; SqlCommand command = new SqlCommand(sql, connection); SqlParameter imageDataParam = new SqlParameter("@ImageData", SqlDbType.VarBinary, -1); imageDataParam.Value = image; command.Parameters.Add(imageDataParam); command.ExecuteNonQuery(); } ``` 上面的代码中,`connectionString`是你的数据库连接字符串,`image_table`是你要保存图片的表名,`image_data`是你要保存图片的列名。 接下来是如何从数据库读取图片显示到窗体上。假设你有一个名为`pictureBox1`的`PictureBox`控件,用于显示图片。以下是一个例子,用于从 SQL Server 数据库中的`image_table`表中读取图片数据,并将其显示到`pictureBox1`上: ```csharp using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT image_data FROM image_table WHERE id = @Id"; SqlCommand command = new SqlCommand(sql, connection); SqlParameter idParam = new SqlParameter("@Id", SqlDbType.Int); idParam.Value = id; command.Parameters.Add(idParam); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { byte[] image = (byte[])reader["image_data"]; MemoryStream stream = new MemoryStream(image); Image img = Image.FromStream(stream); pictureBox1.Image = img; } } ``` 上面的代码中,`id`是你要读取图片的行的 ID。`pictureBox1`是你要显示图片的控件。 希望这些代码可以帮助你实现图片上传和显示的功能。如果你有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值