最近的一个项目需要把截图获得的Image类型的图片文件保存到数据库,通过借鉴其他大牛的代码,外加自己琢磨,简单实现了这一功能。
直接贴出来:
首先需要添加引用
using MySql.Data.MySqlClient;
using System.IO;然后
private void btnSaveTrend_Click(object sender, EventArgs e)
{
byte[] byImage = GetByteImage(image);
string sql = "insert into trend_info values (null, " +...+ ", '" + byImage + "')";
DBHelper.conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, DBHelper.conn);
cmd.Parameters.Add(new MySqlParameter("byImage", MySqlDbType.MediumBlob)).Value = byImage;
int rowCount = cmd.ExecuteNonQuery();
DBHelper.conn.Close();
DBHelper.conn.Dispose();
if (rowCount > 0)
{
MessageBox.Show("保存成功");
}
else
MessageBox.Show("保存失败");
}
//将image转化为二进制
public byte[] GetByteImage(Image img)
{
byte[] bt = null;
if (!img.Equals(null))
{
using (MemoryStream mostream = new MemoryStream())
{
Bitmap bmp = new Bitmap(img);
bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//将图像以指定的格式存入缓存内存流
bt = new byte[mostream.Length];
mostream.Position = 0;//设置留的初始位置
mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
}
}
return bt;
}