Reputation: 18724
I have generated an image in my .Net backend service, and am sitting with a System.Drawing.Image object. 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.
Is there a way I can do something like:
self.Image = ko.observable();
And then load the image from my WebApi call, into self.Image (Not sure what the return type would be).
And then ?
Upvotes: 1
Views: 349
Reputation: 18724
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;" />
Upvotes: 1
Reputation: 2665
It's actually pretty easy. You can use the attr
binding to bind any html attribute. Here's a sample of using a button to do whatever you want (ajax included) to load the image. 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
.
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>
Upvotes: 2