zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

asp.netmvc从数据库中读取图片的实现代码

数据库ASP代码 实现 图片 读取 NetMvc
2023-06-13 09:14:18 时间
首先是创建一个类,继承于ActionResult,记住要引用System.Web.Mvc命名空间,如下:
复制代码代码如下:

publicclassImageResult:ActionResult
{
publicImageFormatContentType{get;set;}
publicImageimage{get;set;}
publicstringSourceName{get;set;}
publicImageResult(string_SourceName,ImageFormat_ContentType)
{
this.SourceName=_SourceName;
this.ContentType=_ContentType;
}
publicImageResult(Image_ImageBytes,ImageFormat_ContentType)
{
this.ContentType=_ContentType;
this.image=_ImageBytes;
}
publicoverridevoidExecuteResult(ControllerContextcontext)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
if(ContentType.Equals(ImageFormat.Bmp))context.HttpContext.Response.ContentType="image/bmp";
if(ContentType.Equals(ImageFormat.Gif))context.HttpContext.Response.ContentType="image/gif";
if(ContentType.Equals(ImageFormat.Icon))context.HttpContext.Response.ContentType="image/vnd.microsoft.icon";
if(ContentType.Equals(ImageFormat.Jpeg))context.HttpContext.Response.ContentType="image/jpeg";
if(ContentType.Equals(ImageFormat.Png))context.HttpContext.Response.ContentType="image/png";
if(ContentType.Equals(ImageFormat.Tiff))context.HttpContext.Response.ContentType="image/tiff";
if(ContentType.Equals(ImageFormat.Wmf))context.HttpContext.Response.ContentType="image/wmf";
if(image!=null)
{
image.Save(context.HttpContext.Response.OutputStream,ContentType);
}
else
{
context.HttpContext.Response.TransmitFile(SourceName);
}
}
}

然后在Controller类中创建一个Action.如下:
复制代码代码如下:

publicActionResultGetPicture(intid)
{
ICategoryserver=newCategoryServer();
byte[]buffer=server.getCategoryPicture(id);
if(buffer!=null)
{
MemoryStreamstream=newMemoryStream(buffer);
System.Drawing.Imageimage=System.Drawing.Image.FromStream(stream);
ImageResultresult=newImageResult(image,System.Drawing.Imaging.ImageFormat.Jpeg);
returnresult;
}
returnView();
}

这样就可以显示图片了。
下面几种方法可以显示已经存在的图片
方法一:
复制代码代码如下:
usingSystem.IO;
publicFileResultImage(){
stringpath=Server.MapPath("/Content/Images/Decorative/");
stringfilename=Request.Url.Segments[Request.Url.Segments.Length-1].ToString();
//UssPath.CombinefromSystem.IOinsteadofStringBuilder.
stringfullPath=Path.Combine(path,filename);
return(newFileResult(fullPath,"image/jpeg"));
}

方法二:
复制代码代码如下:
publicActionResultImage(stringid)
{
vardir=Server.MapPath("/Images");
varpath=Path.Combine(dir,id+".jpg");
returnbase.File(path,"image/jpg");
}

方法三:
复制代码代码如下:
[AcceptVerbs(HttpVerbs.Get)]
[OutputCache(CacheProfile="CustomerImages")]
publicFileResultShow(intcustomerId,stringimageName)
{
varpath=string.Concat(ConfigData.ImagesDirectory,customerId,@"\",imageName);
returnnewFileStreamResult(newFileStream(path,FileMode.Open),"image/jpeg");
}

这三种都可以显示已经存在的图片并且我认为第三种方法可以修改为从数据库中读取图片显示。