您的当前位置:首页正文

C#(WinForm)上传图片保存到数据库和从数据库读取图片显示到窗体

2023-11-09 来源:帮我找美食网

//浏览图片 2 3 private void btnUp_Click(object sender, EventArgs e) 4 5 { 6 7 OpenFileDialog ofd = new OpenFileDialog(); 8 9 ofd.Title = "选择要上传的图片"; 10 11 ofd.Filter = "All Files(*.*)|*.*|位图(*.bmp)|*.bmp|JPEG(*.jpg)|*.jpg"; 12 13 ofd.ShowDialog(); 14 15 textBox1.Text = ofd.FileName; 16 17 if (!File.Exists(ofd.FileName)) 18 19 { 20 21 MessageBox.Show("照片为空"); 22 23 return; 24 25 } 26 27 } 28 29 30 31 32 33 //上传保存到数据库 34 35 private void btnUpLoad_Click(object sender, EventArgs e) 36 37 { 38 39 string strPath = txtbImage.Text.Trim(); 40 41 FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read); 42 43 byte[] byteFile = new byte[fs.Length]; 44 45 fs.Read(byteFile, 0, (int)fs.Length); 46 47 fs.Close(); 48 49 SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"); 50 51 try 52 53 { 54 55 SqlCommand cmd = new SqlCommand(); 56 57 cmd.Connection = conn; 58 59 60 61 string strSql = "insert into test(FileName,Img) Values(@FileName,@Img)"; 62 63 cmd.CommandText =strSql ; 64 65 //cmd.Parameters.AddWithValue("@FileName", strPath); 66 67 //cmd.Parameters.AddWithValue("@Img", byteFile); 68 69 //或者 70 71 SqlParameter[] parameters = new SqlParameter[2]; 72 73 parameters[0] = new SqlParameter("@FileName", SqlDbType.NVarChar, 200); 74 75 parameters[0].Value = strPath; 76 77 parameters[1] = new SqlParameter("@Img", SqlDbType.Image,int.MaxValue); 78 79 parameters[1].Value = byteFile; 80 81 cmd.Parameters.AddRange(parameters); 82 83 conn.Open(); 84 85 cmd.ExecuteNonQuery(); 86 87 conn.Close(); 88 89 MessageBox.Show("上传成功"); 90 91 } 92 93 catch 94 95 { 96 97 conn.Close(); 98 99 MessageBox.Show("上传失败!");100 101 }102 103 }104 105 从数据库读取图片显示到窗体:106 1107 2108 3109 4110 5111 6112 7113 8114 9115 10116 11117 12118 13119 14120 15121 16122 17123 18124 19125 20126 21127 22128 23129 24130 25131 26132 27133 28134 29135 30136 31137 32138 33139 34140 35141 36142 37143 38144 39145 40146 41147 42148 43149 44150 45151 46152 47153 48154 49155 50156 51157 52158 53159 54160 55161 56162 57163 58164 59165 60166 61167 62168 63169 64170 65171 66172 67173 68174 69175 70176 71177 72178 73179 //读到图片显示到PictureBox180 181 private void btnDownLoad_Click(object sender, EventArgs e)182 183 {184 185 byte[] bytFile;186 187 SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");188 189 try190 191 {192 193 SqlCommand cmd = new SqlCommand();194 195 string strSql = "select img from test where ID=3";196 197 cmd.Connection = conn;198 199 cmd.CommandText = strSql;200 201 conn.Open();202 203 SqlDataReader sdr = cmd.ExecuteReader();204 205 if (sdr.Read())206 207 {208 209 bytFile = (Byte[])sdr["Img"];210 211 }212 213 else214 215 {216 217 bytFile = new byte[0];218 219 }220 221 sdr.Close();222 223 conn.Close();224 225 //通过内存流MemoryStream,226 227 //把byte[]数组fileContent加载到Image中并赋值给图片框的Image属性,228 229 //让数据库中的图片直接显示在窗体上。230 231 MemoryStream ms = new MemoryStream(bytFile, 0, bytFile.Length);232 233 this.picImage.Image = Image.FromStream(ms);234 235 //关闭内存流236 237 ms.Close();238 239 }240 241 catch242 243 {244 245 conn.Close();246 247 MessageBox.Show("失败");248 249 }250 251 }

代码转自IT学习广场http://www.itxxgc.com/net/detail/30

                 来自凌波小屋-----冯和超的笔记-------

C#(WinForm)上传图片保存到数据库和从数据库读取图片显示到窗体

标签:

小编还为您整理了以下内容,可能对您也有帮助:

C#WinForm中,用于将图片以二进制存入sql数据库中,并将图片从数据库中取出,显示在PictureBox控件中。

插入: //单击图片选择添加的图片 private void pic_Click(object sender, EventArgs e)

{ dlg.Filter = "JPG|*.jpg|BMP|*.bmp|PNG|*.png";

if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{

pic.Image = Image.FromFile(dlg.FileName);

txtFilePath = dlg.FileName;

}

} public byte[] picData; public string txtFilePath = ""; 添加确定按钮代码: f (txtFilePath != "")

{

try

{

FileStream fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read);

int len = Convert.ToInt32(fs.Length);

b = new byte[len];

fs.Read(b, 0, len);

fs.Close();

}

catch

{

b = null;

}

} SqlConnection conn = new SqlConnection(strConn);

conn.Open(); SqllCommand cmdInsert = new SqlCommand();

cmdInsert.Connection = conn;

cmdInsert.CommandText =插入语句; cmdInsert.Parameters.Add("@照片", SqlDbType.Image); if (txtFilePath == "")

{

cmdInsert.Parameters["@照片"].Value = DBNull.Value;

}

else

{

cmdInsert.Parameters["@照片"].Value = b;

}

cmdInsert.ExecuteNonQuery();

conn.Close();获取: public byte[] picData; SqlConnection conn = new SqlConnection(strConn);

SqlCommand cmd = new SqlCommand();

cmd.Connection = conn;

cmd.CommandText = "select * from 联系人 where 编号=" + ID.ToString();

SqlDataAdapter sda = new SqlDataAdapter(cmd);

DataSet ds = new DataSet(); sda.Fill(ds); if (ds.Tables[0].Rows.Count == 1)

{

if (ds.Tables[0].Rows[0]["照片"] == DBNull.Value)

{ //pic为picturebox控件

pic.Image = PhoneBoook.Properties.Resources.DeskShade;//为空的话给个默认图片

}

else

{

byte[] b = (byte[])(ds.Tables[0].Rows[0]["照片"]);

pic.Image = Image.FromStream(new MemoryStream(b));

picData = b;

}

}

c#图片上传数据库代码怎么写?

下面是C#代码,它将图像上传到SQL Server数据库:
using System;
using System.Data.SqlClient;
using System.IO;
namespace ImageUploadToSQL
{
class Program
{
static void Main(string[] args)
{
// 定义数据库连接字符串
string connectionString = "Data Source=localhost;Initial Catalog=DB_NAME;Integrated Security=True";
string filePath = @"C:\your_image.jpg"; // 图像文件路径
try
{
// 读取图像文件
byte[] image = File.ReadAllBytes(filePath);
// 创建数据库连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 插入图像数据到数据库
using (SqlCommand command = new SqlCommand("INSERT INTO Images (ImageData) VALUES (@ImageData)", connection))
{
command.Parameters.AddWithValue("@ImageData", image);
command.ExecuteNonQuery();
}
}
Console.WriteLine("图像上传成功");
}
catch (Exception ex)
{
Console.WriteLine("图像上传失败:" + ex.Message);
}
}
}
}
首先,该代码读取图像文件,将其转换为字节数组,然后使用SqlConnection和SqlCommand类执行插入操作,将字节数组插入到数据库表中。注意,您需要将数据库连接字符串替换为您自己的数据库连接信息,并确保数据库表已经正确创建,例如:
CREATE TABLE Images (
ImageID INT IDENTITY(1,1) PRIMARY KEY,
ImageData VARBINARY(MAX)
);

c#图片上传数据库代码怎么写?

下面是C#代码,它将图像上传到SQL Server数据库:
using System;
using System.Data.SqlClient;
using System.IO;
namespace ImageUploadToSQL
{
class Program
{
static void Main(string[] args)
{
// 定义数据库连接字符串
string connectionString = "Data Source=localhost;Initial Catalog=DB_NAME;Integrated Security=True";
string filePath = @"C:\your_image.jpg"; // 图像文件路径
try
{
// 读取图像文件
byte[] image = File.ReadAllBytes(filePath);
// 创建数据库连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 插入图像数据到数据库
using (SqlCommand command = new SqlCommand("INSERT INTO Images (ImageData) VALUES (@ImageData)", connection))
{
command.Parameters.AddWithValue("@ImageData", image);
command.ExecuteNonQuery();
}
}
Console.WriteLine("图像上传成功");
}
catch (Exception ex)
{
Console.WriteLine("图像上传失败:" + ex.Message);
}
}
}
}
首先,该代码读取图像文件,将其转换为字节数组,然后使用SqlConnection和SqlCommand类执行插入操作,将字节数组插入到数据库表中。注意,您需要将数据库连接字符串替换为您自己的数据库连接信息,并确保数据库表已经正确创建,例如:
CREATE TABLE Images (
ImageID INT IDENTITY(1,1) PRIMARY KEY,
ImageData VARBINARY(MAX)
);

C#winform 中上传图片保存到数据库中?

就是2中方法:

1:上传图片的相对路径到数据库中相应字段里,读取显示时,将控件(假设用的是Image控件)的ImageUrl属性指向该相对路径即可。

2:将图片以二进制流的方式整体上传到数据库里,读取显示时,以二进制流的方式整体读出。这种方法稍微麻烦一点,但保存的是图片整体到数据库里。

参考资料:http://apps.hi.baidu.com/share/detail/21838749

C# winForm怎么把pictureBox显示的图片放到数据库中和从数据库中读取出来显示到pictureBox中

你最好用 地址 放图片。 二进制的话给你

这是上传图片 代码:

Stream aa;

OpenFileDialog opg = new OpenFileDialog();

if (opg.ShowDialog() == DialogResult.OK)

{

pictureBox2.Load(opg.FileName);//获取要上传的图片

aa= opg.OpenFile();

}

string con = "data source=.;uid=sa;pwd=;database=master";

SqlConnection conn = new SqlConnection(con);

byte[] bytes = new byte[aa.Length];

aa.Read(bytes, 0, (int)aa.Length);

conn.Open();

string sql1 = string.Format("insert into 数据库表格 values('{0}',@phone)", 用户名);

SqlCommand cmd1 = new SqlCommand(sql1, conn);

cmd1.Parameters.Add("@phone", SqlDbType.Image).Value = bytes;

cmd1.ExecuteNonQuery();

conn.Close();

MessageBox.Show( "用户名的图片已上传");

从数据库得到二进制图片,转化为pictrue:

string sql = "select 图片 from 数据库表格 where name=用户名";

SqlConnection conn = new SqlConnection("data source=.;uid=sa;pwd=****;database=master");

SqlCommand cmd = new SqlCommand(sql,conn);

conn.Open();

byte[] bs = (byte[])r["图片"];

MemoryStream ms = new MemoryStream(bs, true);

ms.Write(bs, 0, bs.Length);

pictureBox1.Image = new Bitmap(ms, true);

ms.Dispose();

conn.close();

最重要要能理解代码,懂了就简单了。 希望采纳。

Top