using Microsoft.Data.SqlClient; using System.Data; namespace PhotoApp; internal class PhotoHelper { string createTableSql = @"CREATE TABLE [dbo].[Employee]( [emp_id] [int] NOT NULL, [emp_name] [varchar](50) NOT NULL, [emp_image] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]"; string connectionString = "Server=192.168.10.xxx;User Id=xxx;Password=xxx;Database=TestPhoto;Trusted_Connection=false;TrustServerCertificate=True"; public string getPhotoPath = @"D:\Dragon.png"; public string savePhotoPath = @"D:\test.png"; public void SavePhotoToSqlServer() { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { FileInfo finfo = new FileInfo(getPhotoPath); byte[] btImage = new byte[finfo.Length]; FileStream fStream = finfo.OpenRead(); fStream.Read(btImage, 0, btImage.Length); fStream.Close(); using (SqlCommand sqlCommand = new SqlCommand( "INSERT INTO Employee (emp_id, emp_name, emp_image) VALUES(@emp_id, @emp_name, @emp_image)", sqlConnection)) { sqlCommand.Parameters.AddWithValue("@emp_id", 2); sqlCommand.Parameters.AddWithValue("@emp_name", "Employee Name"); SqlParameter imageParameter = new SqlParameter("@emp_image", SqlDbType.Image); imageParameter.Value = btImage; sqlCommand.Parameters.Add(imageParameter); sqlConnection.Open(); sqlCommand.ExecuteNonQuery(); sqlConnection.Close(); } } } public string createTableSql2 = @"CREATE TABLE [dbo].[ImageFile]( [Id] [UNIQUEIDENTIFIER] NOT NULL, [Name] [NVARCHAR](200) NULL,--文件名 [Type] [NVARCHAR](50) NULL,--文件类型 [Image] [IMAGE] NULL--文件 )"; public void SaveBulkPhotosToSqlServer() { using (SqlConnection myconn = new SqlConnection(connectionString)) { myconn.Open(); using (SqlCommand mycomm = new SqlCommand()) { DirectoryInfo dir = new DirectoryInfo(savePhotoPath); foreach (FileInfo item in dir.GetFiles("*.png"))//循环读取文件夹内的png文件 { //var pic = getJpgSize(item.FullName); string str = string.Format("insert into ImageFile (Id,Name,Type,Image) values('{0}','{1}','{2}',@Image)", Guid.NewGuid().ToString(), Path.GetFileNameWithoutExtension(item.FullName), item.Extension.Substring(1));//插入数据 mycomm.CommandText = str; mycomm.Connection = myconn; FileStream fs = new FileStream(item.FullName, FileMode.Open); BinaryReader br = new BinaryReader(fs); Byte[] byData = br.ReadBytes((int)fs.Length); fs.Close(); mycomm.Parameters.Add("@Image", SqlDbType.Binary, byData.Length); mycomm.Parameters["@Image"].Value = byData; mycomm.ExecuteNonQuery(); mycomm.Parameters.Clear(); } } } } public void ReadPhotoFromSqlServer(int userId) { using (SqlConnection sqlconnection = new SqlConnection(connectionString)) { sqlconnection.Open(); string sqlQuery = string.Format(@"Select [emp_image] From [Employee] Where [emp_id]={0}", userId); // Read Image Value from Sql Table SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlconnection); using (SqlDataReader reader = sqlCommand.ExecuteReader()) { if (reader.HasRows) { //声明一字节数组 将数据库中的图片现存入字节数组中 byte[] imageByte; //在这我是知道里面就一张图,所以这么写的,个人根据实际情况,可做修改 while (reader.Read()) { //将图片转换为字节数组 imageByte = (byte[])reader["emp_image"]; //转换为文件流 MemoryStream ms = new MemoryStream(imageByte); ms.Seek(0, SeekOrigin.Begin); using (var output = File.OpenWrite(savePhotoPath)) { ms.CopyTo(output); } ////再将文件流转换为图像 //Bitmap bitmap = new Bitmap(stream); //pictureBox1.Image = bitmap; } } } } } public void SaveImageFromBase64(string base64string) { byte[] b = Convert.FromBase64String(base64string); //实际情况需要根据base64判断文件后缀名 string path = Path.Combine(savePhotoPath, "test", "abc.jpg"); File.WriteAllBytes(path, b); } }
参考资料:
Saving an Image to SQL Server - CodeProject
SQLserver用Image格式储存图片 - Murphy丶悦 - 博客园 (cnblogs.com)
关于c#:将MemoryStream转换为FileStream时FileStream数据不完整 | 码农家园 (codenong.com)
标签:core,string,mycomm,数据库,emp,using,new,Image,图片 From: https://www.cnblogs.com/hellowzl/p/17223527.html