您的位置:首页 > 数据库

C#用LINQ to SQL把PictureBox中的图片存入数据库和取出数据库中的图片并显示在PictureBox中

2014-02-21 20:04 501 查看
最近在做一个项目需要用LINQ to SQL把图片存如数据库并且取出数据库,在晚上找了很多资料,大多都是用ADO.NET,感觉ADO.NET有点麻烦,所以没采用,最后研究了下LINQ to SQL,发现依然那么简洁,现在贴出部分代码,如果有什么问题,希望能给我点建议,写的有点急,有些代码可能不是很完美

界面有点丑,但是能用就好啦


下面的是我的查找特定图片并转化成字符数组的方法

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);
}
}
到此我的工作就完成了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐