asp.net-web-apixamarinxamarin-zebblezebble

Return an image from asp.net web api to zebble


I'm trying to return an image from web API to zebble like this:

web api:

    public HttpResponseMessage GetImage()
    {
        var memoryStream = custom logic to create image

        var result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(memoryStream.ToArray());
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
        return result;
    }

zebble:

var imageData = await Get<byte[]>(url);
var imageView = new ImageView { ImageData = imageData }

But the Get throws an exception:

Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'System.Exception' in Zebble.UWP.dll
Exception thrown: 'System.Exception' in mscorlib.ni.dll
ERROR: HttpGet -> 'url' failed.
WARNING: Failed to convert API response to Byte[]

###############################################
Base issue: Unexpected character encountered while parsing value: �. Path '', line 1, position 1.

--------------------------------------
STACK TRACE:

at Zebble.Framework.BaseApi.<GetFromTheServer>d__24`1.MoveNext()

   at Zebble.Framework.BaseApi.<Get>d__25`1.MoveNext()

Any idea how to fix this?


Solution

  • Your WebApi must return string. You can use Base64 string to transfer the image data.

    Step 1: Change your Web API code to:

    var memoryStream = new MemoryStream(); //TODO: custom logic to create image    
    image.Save(memoryStream, ImageFormat.Png);
    return Ok(Convert.ToBase64String(memoryStream.ToArray()));
    

    More details: http://zebble.net/docs/get-apis

    Step 2: In your Zebble code, use the Zebble WebAPI proxy to call your WebAPI to receive the Base64 string back, convert to byte[] and set as the source of your ImageView:

    var base64 = await Api.Get<string>(url);
    var imageData = Convert.FromBase64String(base64);
    myImageView.ImageData = imageData;
    

    More details: http://zebble.net/docs/calling-a-get-api-in-the-mobile-app