首页 > 代码库 > 图片存入数据库并取出显示
图片存入数据库并取出显示
/// <summary>
/// 将图片转成二进制
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static byte[] ImageDatabytes(string FilePath)
{
if (!File.Exists(FilePath))
{
return null;
}
Bitmap myBitmap = new Bitmap(System.Drawing.Image.FromFile(FilePath));
using (MemoryStream curImageStream = new MemoryStream())
{
myBitmap.Save(curImageStream, System.Drawing.Imaging.ImageFormat.Png);
curImageStream.Flush();
byte[] bmpBytes = curImageStream.ToArray();
//如果转字符串的话
//string BmpStr = Convert.ToBase64String(bmpBytes);
return bmpBytes;
}
}
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; HttpServerUtility server = context.Server; HttpRequest request = context.Request; HttpResponse response = context.Response; HttpPostedFile file = null; if (context.Request.Files != null && context.Request.Files.Count > 0) { file = context.Request.Files[0]; if (file.ContentLength > 0) { string extName = Path.GetExtension(file.FileName); string fileName = Guid.NewGuid().ToString(); string fullName = fileName + extName; string imageFilter = ".jpg|.png|.gif|.ico";// 随便模拟几个图片类型 if (imageFilter.Contains(extName.ToLower())) { string phyFilePath = server.MapPath("~/Upload/Image/") + fullName; file.SaveAs(phyFilePath); bool flage = IntoSQL(request, response); //存数据库 if (flage) { response.Write("<script>alert(‘上传成功‘);history.back()</script>"); //response.Write("<script language=javascript>history.go(-2);</script>"); //response.Write("上传成功!文件名:" + fullName + "<br />"); //response.Write(string.Format("<img src=http://www.mamicode.com/‘Upload/Image/{0}‘/>", fullName)); } } } } }
借助一般应用程序,页面前端image标签把src指向“一般应用程序” 可以传相应的参数,来确定显示哪一张
<img src=http://www.mamicode.com/"AppService/EditPicture.ashx?GOODSID=<%=goodsID %>" class="miniztpic" alt="" />
一般应用程序主要代码如下:
public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string goodsID = context.Request.QueryString["GOODSID"]; WeChatBLL.ItemsListBLL itemsListBLL = new WeChatBLL.ItemsListBLL(); System.Collections.Generic.List<MemberShip.ReplacementItem> replacementItemList = itemsListBLL.GetReplacementItemList(); //查询数据库所以图片 Object o = ""; if (goodsID == null || goodsID == "") { //o = voucherEditorContext.Voucher.VoucherData.Tables["GOODSINFO"].Rows[0][scenePropertyDetail.PropertyCode]; } else { foreach (var item in replacementItemList) //循环图片列表 { if (item.ItemID == goodsID) //当图片id相等时 { if (item.ItemPhotos != null) { o = item.ItemPhotos[0]; //直接把数据库二进制赋值给o } } } } if (o is DBNull || o.ToString() == "") { return; } else { byte[] image = (Byte[])o; context.Response.BinaryWrite(image); //返回二进制图片,页面会自动显示 } }
图片存入数据库并取出显示