如何将图片录入到数据库中?
现,正在构建一数据录入界面使用vs2005 C#中文版+SQLServer2000中文版 winxp平台。
要求:将图片录入到数据库中,数据库中相应的存储图片字段数据类型为:Image
不知道在C#中,使用哪种控件可以将图片录入到数据库中。具体的原理请说说。谢谢
------解决方案-------------------- <%@ WebHandler Language= "C# " Class= "Handler " %>
using System;
using System.IO;
using System.Web;
public class Handler : IHttpHandler {
public bool IsReusable {
get {
return true;
}
}
public void ProcessRequest (HttpContext context) {
// 设置响应设置
context.Response.ContentType = "image/jpeg ";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
// 设置 Size 参数
PhotoSize size;
switch (context.Request.QueryString[ "Size "]) {
case "S ":
size = PhotoSize.Small;
break;
case "M ":
size = PhotoSize.Medium;
break;
case "L ":
size = PhotoSize.Large;
break;
default:
size = PhotoSize.Original;
break;
}
// 设置 PhotoID 参数
Int32 id = -1;
Stream stream = null;
if (context.Request.QueryString[ "PhotoID "] != null && context.Request.QueryString[ "PhotoID "] != " ") {
id = Convert.ToInt32(context.Request.QueryString[ "PhotoID "]);
stream = PhotoManager.GetPhoto(id, size);
} else {
id = Convert.ToInt32(context.Request.QueryString[ "AlbumID "]);
stream = PhotoManager.GetFirstPhoto(id, size);
}
// 从数据库获取照片,如果未返回照片,将获取默认的“placeholder”照片
if (stream == null) stream = PhotoManager.GetPhoto(size);
// 将图像流写入响应流中
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0) {
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}
}
------解决方案--------------------存图片代码:
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
cmd.Parameters.Add( "@studentPhoto ", SqlDbType.Image).Value = imagebytes;
读取图片代码:
// 显示图片
if(myReader[ "studentPhoto "].ToString() != " ")// 如果图片字段不为空时显示图片数据
{
imagebytes = (byte[]) (myReader[ "studentPhoto "]);
studentAbout.Text = myReader[ "studentAbout "].ToString(); // 预先显示一下附注信息,免得数据库图片字段有值,但不是图片时产生异常而不执行下面的内容。
if (imagebytes.Length > 0)
{
MemoryStream stream = new MemoryStream(imagebytes, true); // 创建一个内存流,支持写入,用于存放图片二进制数据
try
{
stream.Write(imagebytes, 0, imagebytes.Length);
Bitmap FinalImage = new Bitmap(stream);
this.studentPhoto.Image = FinalImage;
this.studentPhoto.Refresh();
}
finally
{
stream.Close();
}
}
}
------解决方案--------------------点击一个Button,将选中的图片上传到数据库中:
protected void updateButton_Click(object sender, EventArgs e)
{
SqlConnection conn = SqlBD.Opened_connnection(connStrLabel.Text);//创建连接
//获取上传图片的参数
string filename = Path.GetFileName(chooseFile.PostedFile.FileName);
string filepath = Server.MapPath( "~\\临时文件夹\\ " + filename);