简体   繁体   English

从WebAPI调用显示图像

[英]Display an Image from a WebAPI call

I have generated an image in my .Net backend service, and am sitting with a System.Drawing.Image object. 我在.Net后端服务中生成了一个图像,并且正在使用System.Drawing.Image对象。 I made a call to my WebAPI method, rendered the image, and would like to return the image to the front end, and display it. 我调用了我的WebAPI方法,渲染了图像,并希望将图像返回到前端,然后显示它。

Is there a way I can do something like: 有没有办法可以做类似的事情:

self.Image = ko.observable(); self.Image = ko.observable();

And then load the image from my WebApi call, into self.Image (Not sure what the return type would be). 然后将我的WebApi调用中的图像加载到self.Image(不确定返回类型是什么)。

And then ? 接着 ?

It's actually pretty easy. 这实际上非常简单。 You can use the attr binding to bind any html attribute. 您可以使用attr绑定绑定任何html属性。 Here's a sample of using a button to do whatever you want (ajax included) to load the image. 以下是使用按钮执行任何操作(包含ajax)来加载图像的示例。 Side note, I'm not really sure what your image is coming back as, but you certainly can use data urls to bind as the src . 旁注,我不确定你的图像是什么回来,但你当然可以使用数据网址绑定为src

 function viewModel() { var self = this; self.Image = ko.observable(); self.LoadImage = function() { // Ajax stuff self.Image("http://lorempizza.com/200/200"); } } ko.applyBindings(new viewModel()) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <img data-bind="attr: {src: Image} "> <button data-bind="click: LoadImage">Load Image </button> 

I worked it out: 我解决了这个问题:

[Route("Preview"), HttpPost]
        public string Preview(PlateTemplateExtendedDto data)
        {
            var img = new PlateService().CreateTemplate(true);
            using (var ms = new MemoryStream())
            {
                img.Save(ms, ImageFormat.Jpeg);
                var base64 = "data:image/jpeg;base64," + Convert.ToBase64String(ms.ToArray());
                return base64;
            }
        }

And then on the view, I just use that text as the source. 然后在视图中,我只使用该文本作为源。

<img data-bind="attr:{src: image}" class="img-responsive" style="margin: 0 auto;" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM