asp.net(c#)实现从sqlserver存取二进制图片的代码
2024-07-10 12:41:45
供稿:网友
下面说说主要实现思路:
1、存取图片
(1)、将图片文件转换为二进制并直接存进sql server
代码如下:
//UploadHelper.cs
/// <summary>
/// 将图片转化为长二进制
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static Byte[] SetImgToByte(string imgPath)
{
FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
Byte[] byteData = new Byte[file.Length];
file.Read(byteData, 0, byteData.Length);
file.Close();
return byteData;
}
/// <summary>
/// 将转换成二进制码的图片保存到数据库中
/// </summary>
public static bool SaveEmployeeImg2Db(Employee model, string path)
{
try
{
Byte[] imgBytes = SetImgToByte(path);
model.Photo = imgBytes;
bool flag=EmployeeService.SaveEmployeePhoto(model); //EmployeeService是公司内部的库调用,插入或者更新照片,这里不透露细节
return flag;
}
catch (Exception ex)
{
throw ex;
}
}
(2)、在网页中上传图片
代码如下:
/// <summary>
/// 上传图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
string serverPath = Server.MapPath("~/images/");
if (this.fuPhoto.HasFile) //fuPhoto是fileupload控件
{
string fileName = this.fuPhoto.PostedFile.FileName;
FileInfo fi = new FileInfo(fileName);
string mimeType = this.fuPhoto.PostedFile.ContentType.ToLower();
if (mimeType.IndexOf("image") < 0)
{
//("上传的照片格式不对");
}
else if(fi.Length > 2* 1024 * 1024)
{
//图片大于2M,重新处理
}
else
{
string saveFilePath = serverPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileName;
try
{
//先存图片到服务器
this.fuPhoto.PostedFile.SaveAs(saveFilePath);
//转成二进制
Employee model = new Employee(int.Parse(id)); //id是EmployeeId,这里是模拟字段
bool flag = UploadHelper.SaveEmployeeImg2Db(model, saveFilePath);
}
catch
{
//("照片上传失败");
}
finally
{
//最后删掉该图片
if (System.IO.File.Exists(saveFilePath))
{
System.IO.File.Delete(saveFilePath);
}
}
}
}
else
{
//("全选择要上传的照片");
}
}
(3)、从数据库取出照片(返回格式Image)
代码如下:
//UploadHelper.cs
/// <summary>
/// 将二进制转化为图片Image
/// </summary>
/// <param name="photopath"></param>
/// <returns></returns>
public static System.Drawing.Image GetImgFromByte(Employee model)
{
System.Drawing.Image img = null;
try
{
Stream stream = new MemoryStream(model.Photo);
img = System.Drawing.Image.FromStream(stream,false);