1)将图片插入数据库
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace RichTextBoxDemo
{
public partial class Form1 : Form
{
private DataClasses1DataContext dcdc = new DataClasses1DataContext();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 将图片添加到richtextbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInputImage_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Image Files(*.jpg;*.gif)|*.jpg;*.gif";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string path = fileDialog.FileName;
Clipboard.SetDataObject(Image.FromFile(path), false);
richTextBox1.Paste();
}
}
/// <summary>
/// 将图片添加到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSubmit_Click(object sender, EventArgs e)
{
//将richtextbox中的内容转化正byte数组并在中间加|添加到数据库
StringBuilder sb = new StringBuilder();
byte[] bytes = Encoding.Default.GetBytes(richTextBox1.Rtf);
foreach (byte b in bytes)
{
sb.Append(b + "|");
}
Table_1 item=new Table_1();
item.Content = sb.ToString();
dcdc.Table_1.InsertOnSubmit(item);
dcdc.SubmitChanges();
}
private void btnView_Click(object sender, EventArgs e)
{
Form2 fm = new Form2();
fm.ShowDialog();
}
}
}
2)读取数据库显示图片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RichTextBoxDemo
{
public partial class Form2 : Form
{
private DataClasses1DataContext dcdc = new DataClasses1DataContext();
public Form2()
{
InitializeComponent();
}
/// <summary>
/// 将图片从数据库中读取
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form2_Load(object sender, EventArgs e)
{
//将string以|拆分赋值给byte数组并转化成string在richtextbox中显示
Table_1 item = dcdc.Table_1.SingleOrDefault(u => u.id == 11);
if (item.Content != null)
{
string[] strs = item.Content.Split('|');
int length = strs.Length;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
{
if (strs[i].Trim().Length > 0)
{
bytes[i] = Convert.ToByte(strs[i]);
}
}
if (bytes != null)
{
richTextBox1.Rtf = Encoding.Default.GetString(bytes);
}
}
}
}
}