2015-05-14 64 views
1

我有一个应用程序,用户可以通过文件输入选择图像。选择图像后,我通过AJAX将图像上传到控制器并将其转换为灰度。转换方法返回一个System.Drawing.Image对象。我想要的是在AJAX成功函数上返回这个灰度图像对象,并将其显示在原始图像上传的同一页中的另一个div上。请注意,这个图像从来没有存储在任何地方,所以没有理由在我的控制器中使用文件返回操作。 我能做什么? 问候 路易斯。返回从MVC控制器和显示器的图像类型

回答

1

你会做什么是Base64编码,图像,并将其发送回客户端,然后在客户端做这样的事情在HTML:

<img src="data:image/png;base64,' + data + '" /> 
0
public class ImageResult : ActionResult 
{ 
    private Image Image { get; private set; } 
    private ImageFormat ImageFormat { get; private set; } 

    public ImageResult(Image image, ImageFormat imageFormat = ImageFormat.Png) 
    { 
     if (image == null) throw new ArgumentNullException("image"); 
     this.Image = image; 
     this.ImageFormat = format; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     var httpContext = context.HttpContext; 

     httpContext.Response.Clear(); 
     httpContext.Response.ContentType = this.GetContentType(); 
     this.Image.Save(httpContext.Response.OutputStream, this.ImageFormat); 
    } 

    private String GetContentType() 
    { // borrowed: http://stackoverflow.com/a/15261265/298053 
     var imageCodecInfos = ImageCodecInfo.GetImageEncoders(); 
     var codec = imageCodecInfos.FirstOrDefault(x => x.FormatID == this.ImageFormat.Guid); 
     return codec != null ? codec.MimeType : "application/octet-stream"; 
    } 
} 

然后,你应该能够做到例如:

Image bwImage = /* service call */; 
return new ImageResult(bwImage, ImageFormat.Png);