读取本地图片,将图片以二进制流的形式存储到数据库中
1、成功访问到数据库;
2、设计Form1界面,从工具箱中添加一个按钮button1和一个画板panel1;
3、从本地读取图片的二进制流;
编写函数如下:
public byte[] imageBinary(string imagePath)
{
FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
int bytelen = (int)fs.Length;
byte[] filebytes = new byte[bytelen];
fs.Read(filebytes,0,bytelen);
fs.Close();
return filebytes;
}
4、点击按钮,将读取到的图片二进制流显示到界面画板panel1中,并保存到数据库中。
代码如下:
private void button1_Click(object sender, EventArgs e)
{
panel1.BackgroundImage = Image.FromStream(new MemoryStream(fileBytes));//以二进制流形式显示图片
string strSql = "insert into image_path(id,image_path)values(@id,@image_path)";
Write(strSql, fileBytes); //将图片保存到指定表中
}
public int i = 1;
public void Write(string strSql, byte[] imageBytes)
{
string connStr = "Server = localhost;Database = test;Uid = root;Pwd = 123456";
int id = i++; //每点击按钮插入一条记录,主键自增1
using (MySqlConnection conn = new MySqlConnection(connStr))
{
try
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strSql;
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.Add("@image_path", MySqlDbType.LongBlob).Value = imageBytes;
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
数据库test中的表image_path结构如下:
`id`int(10) NOT NULL,
`image_path`longblob,
PRIMARY KEY (`id`)
注意,存入表中的图片二进制流比较大,字段image_path可设置为Blob类型(单位:字节),用于存储二进制数据:
TinyBlob 最大 255
Blob 最大 65K
MediumBlob 最大 16M
LongBlob 最大 4G
可根据需要存储的图片大小选择
需要注意的是,MySql系统默认存储数据量为1M,存储大于1M的二进制数据需手动修改参数max_allowed_packet的值,修改方法如下:
set global max_allowed_packet = 2*1024*1024*10; //设置MySql存储数据量最大为20M
show VARIABLES like '%max_allowed_packet%'; //查看下max_allowed_packet是否修改成功
也可在my.cnf文件中找到max_allowed_packet进行修改。
完整代码如下:
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;
namespace ImageSqlTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] fileBytes = imageBinary("d:\\pic\\1.jpg");
panel1.BackgroundImage = Image.FromStream(new MemoryStream(fileBytes));
string strSql = "insert into image_path(id,image_path)values(@id,@image_path)";
Write(strSql, fileBytes);
}
//将图片二进制流写入数据库中
public int i = 1;
private void Write(string strSql, byte[] imageBytes)
{
string connStr = "Server = localhost;Database = test;Uid = root;Pwd = 123456";
int id = i++;
using (MySqlConnection conn = new MySqlConnection(connStr))
{
try
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = strSql;
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.Add("@image_path", MySqlDbType.LongBlob).Value = imageBytes;
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
}
运行结果如下:
界面显示:
数据库中的表image_path内容如下(本文点击了两次,则存了两条记录):
到此,成功以图片二进制流读取显示到界面并保存到数据库中。