将存照片的字段设为image类型。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PhotoSQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string sqlCon = "";
private void button1\_Click(object sender, EventArgs e)
{
string url = @"C:\\Users\\jinwei\\Desktop\\tiger.jpg";
byte\[\] dd = GetPictureData(url);
ImgToDB(dd);//保存到数据库中
}
private void button2\_Click(object sender, EventArgs e)
{
ImgDBTo();
}
/// <summary>
/// 保存到数据库
/// </summary>
/// <param name="imgBytesIn"></param>
private void ImgToDB(byte\[\] imgBytesIn)
{
try
{
SqlConnection con = new SqlConnection("server=SDSC2-1,1433;uid=sa;pwd=jinwei;database=web");
con.Open();
SqlCommand cmd = new SqlCommand("insert into aaaa (img) values( @Image ) ;", con);
cmd.Parameters.Add("@Image", SqlDbType.Image);
cmd.Parameters\["@Image"\].Value = imgBytesIn;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("图片上传成功");
}
catch
{
MessageBox.Show("您选择的图片不能被读取或文件类型不对!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
/// <summary>
/// 从数据库中 图片 并且保存到C盘
/// </summary>
public void ImgDBTo()
{
byte\[\] MyData = new byte\[\];
using (SqlConnection conn = new SqlConnection("server=SDSC2-1,1433;uid=sa;pwd=jinwei;database=web"))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select \* from aaaa";
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
object o = sdr\["img"\];
MyData = (byte\[\])sdr\["img"\];//读取第一个图片的位流
int ArraySize = MyData.GetUpperBound();//获得数据库中存储的位流数组的维度上限,用作读取流的上限
FileStream fs = new FileStream(@"c:\\00.jpg", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, , ArraySize);
fs.Close(); //-- 写入到c:\\00.jpg。
conn.Close();
Console.WriteLine("读取成功");//查看硬盘上的文件
}
}
/// <summary>
/// 根据路径将图片转换成 byte\[\]
/// </summary>
/// <param name="imagepath"></param>
/// <returns></returns>
public byte\[\] GetPictureData(string imagepath)
{
/\*\*/
////根据图片文件的路径使用文件流打开,并保存为byte\[\]
FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
byte\[\] byData = new byte\[fs.Length\];
fs.Read(byData, , byData.Length);
fs.Close();
return byData;
}
}
}
转载来源:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章