Craig Craig - 12 days ago 5
C# Question

Image->JSON->.Net Image

I am trying to learn Knockout and trying to create a photo uploader. I have successfully stored some images in an Array. Now I want to post back. In my knockout code (Javascript), I do this:

I have an image 'class' in Javascript:

// The image object that wukk be posted back.
function Image(_Image, _Description, _Filesize, _Filetype) {
var self = this;
self.Image =_Image;
self.Description = _Description;
self.Filesize = _Filesize;
self.Filetype = _Filetype;

self.DisplaySize = ko.computed(function () {
SizeToText(self.Filesize);
});
}


I have an array of these in a property called 'images'.

When I click the save button, I try to simply stringify the array of images into 'object'.

var object = JSON.stringify({
images: self.images(),
});


I then post my object back to my .net WebAPI controller.

var uri = "/api/Photo/Upload";
$.post({ url: uri, contentType: "application/json" }, object)
.done(function (data) {
self.images.removeAll();
});


My method gets called, and I can see in the data it receives, all the image data, descriptions etc.

The method is defined as:

public int Upload(UIImageUploadList data)


And a UIImageUploadList is a class that holds a list of images:

public class UIImageUploadList
{
public List<UIImageUpload> Images { get; set; }
}


and UIImageUpload is:

public class UIImageUpload
{

public string Image { get; set; }
public string Description { get; set; }
public string FileType { get; set; }
public int FileSize { get; set; }

}


So, I try and parse the data from the 'data' field, so that I can pass it to my service/logic/data layer.

foreach(var p in data.Images)
{
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var routes_list =
json_serializer.DeserializeObject(p.Image);


byte[] bytes = Convert.FromBase64String(p.Image);

Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}

photos.Add(new Photo
{
Description = p.Description,
PhotoData = image
});
}


But it's in Base64, I think. (JSON.Stringify did that I believe).

The image property starts with this:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJY


and ends with:

AElFTkSuQmCC"


I know if it's JPG or a BMP etc.

In .Net, I try to change this into an Image type, to pass to my DB.

But it fails "DeserializeObject" saying that 'data is not a primitive JSON type'.

How should I be converting to an image that will finally be stored in the database?

Answer

Before calling Convert.FromBase64String, you will need to split the string containing the encoded image data. First, strip of the data:, then you get the MIME type for the image (image/png), then the encoding (base64) and only the remainder of the string (after the comma) can be passed into the conversion function. I don't have much experience with C# but from there on the FromStream function should be smart enough to deal with the decoded data.