您建议使用哪种方法将图片保存到数据库中(SQL 08)? [英] what method do you suggest to save picture into database(SQL 08)?

查看:82
本文介绍了您建议使用哪种方法将图片保存到数据库中(SQL 08)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我有一些图片必须存储到数据库中,但我不希望数据库大小增加太多,现在您建议采用什么方法将图片保存到数据库中?

hi every body,
i have some pictures that must be stored into database but i dont want the database size increases too much, now what method do u suggest to save picture into database?

推荐答案

图像通常很大,因此除非设置了很大的初始大小或大小增量,否则几乎不可能阻止数据库变大.
插入很容易:
1)将图像转换为字节数组(或将其读取为字节数组)
Images tend to be large, so preventing you database from getting bigger is pretty much impossible, unless you set a very large initial size or size increment.
Inserting is easy:
1) Convert your image to a byte array (or read it as a byte array)
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
byte[] data = ms.ToArray();


2)使用SQL插入通过参数化查询将字节保存到Image字段中:


2) Use SQL Insert to save the bytes into an Image field with a Parameterized query:

SQLCommand cmd = ("INSERT INTO myTable (imageData) VALUES (@IM)", con);
cmd.Parameters.AddWithValue("@IM", data);
cmd.ExecuteNonQuery();


尝试一下:



FileUpload img =(FileUpload)imgUpload;
Byte [] imgByte = null;
如果(img.HasFile&&img.PostedFile!= null)
{
//创建一个PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//使用文件len
创建字节数组 imgByte =新的Byte [File.ContentLength];
//强制控件将数据加载到数组中
File.InputStream.Read(imgByte,0,File.ContentLength);
}
//将员工姓名和图像插入db
字符串conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
connection =新的SqlConnection(conn);

connection.Open();
字符串sql ="INSERT INTO EmpDetails(empname,empimg)VALUES(@enm,@eimg)SELECT @@ IDENTITY";
SqlCommand cmd =新的SqlCommand(sql,连接);
cmd.Parameters.AddWithValue("@ enm",txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@ eimg",imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format(员工ID为{0}",ID);
try this :



FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);


这篇关于您建议使用哪种方法将图片保存到数据库中(SQL 08)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆