LINQ to SQL把图片存入数据库,再取出数据库通过PictureBox显示在WinForm界面
- 查找特定图片并转化成字符数组的方法
private byte[] OPenPic()
{
//选择文件
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
//文件格式
openFileDialog.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.png|*.png";
//还原当前目录
openFileDialog.RestoreDirectory = true;
//默认的文件格式
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string path = openFileDialog.FileName;
FileStream fs = new FileStream(path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] imagebytes=new byte[fs.Length];
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
return imagebytes;
}
else
{
return null;
}
}
- 把图片显示在PictureBox中,用下面的方法将获得的字符数组转换成Bitmap类型就可以在PictureBox中
//将字符数组转换成用于处理由像素的数据
private Bitmap GetData(byte[] imagebytes)
{
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmtp = new Bitmap(ms);
return bmtp;
}
- 把PictureBox中的图片用LINQ to SQL存入数据库中
//向数据库中添加文本和图片数据
private void button1_Cluick(object sender, EventArgs e)
{
try
{
DataClassesDataContext dcdc = new DataClassesDataContext();
TextEvolution te = new TextEvolution();
te.SID = Convert.ToInt32(sid.Text);
te.Character = character.Text;
te.Text = text.Text;
te.Notes = notes.Text;
te.MinImage = imagebytes1;
te.MaxImage = imagebytes2;
dcdc.TextEvolution.InsertOnSubmit(te);
dcdc.SubmitChanges();
MessageBox.Show("添加成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
- 用LINQ to SQL把数据库中的数据取出显示在PictureBox中
//从数据库中取出制定文本和图像
private void button_Click(object sender, EventArgs e)
{
Form1 m=new Form1;
try
{
DataClassesDataContext dcdc = new DataClassesDataContext();
var te = dcdc.TextEvolution.FirstOrDefault(o => o.SID == Convert.ToInt32(sid.Text.Trim()));
if (te == null)
{
MessageBox.Show("ERROr");
}
character.Text = te.Character;
text.Text = te.Text;
notes.Text = te.Notes;
picmin1.Image = m.GetData(te.MinImage.ToArray());
picmax1.Image = m.GetData(te.MaxImage.ToArray());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}