Returning an image as part of a JSON response

571 views
Skip to first unread message

Mark Swiatek

unread,
Jun 19, 2012, 11:19:07 AM6/19/12
to servic...@googlegroups.com
Given a class like this:
public class UserDto
{
    public int Id { get;set; }
    public string Name { get; set; }
    public Bitmap Picture {get; set; }
}

I can make a request using the XmlServiceClient and use an ImageConverter to convert the image to a byte array that can be returned to a (partial) view as File(imgArray, "image/jpg"). I haven't been able to do the same with the JsonServiceClient. It appears to serialize differently, Does the Json serializer use a different enconding?

Demis Bellot

unread,
Jun 19, 2012, 1:45:56 PM6/19/12
to servic...@googlegroups.com
There's no support for Bitmap in the ServiceStack JSON + JSV serializers, you can either send a pull request to add it or return a byte[] in the DTO instead. 

But with any text serializer any binary data needs to be encoded (e.g. Base64) which is less efficient than returning it directly.
For this reason I don't like encoding binary payloads and will write images directly to the response stream, e.g. here's 3 different ways you can return an image from a service:

You could also download the file as an attachment if you want to add additional metadata:
new HttpResult(targetFileInfo, asAttachment:true);


Cheers,

Mark Swiatek

unread,
Jun 19, 2012, 1:54:44 PM6/19/12
to servic...@googlegroups.com
I was coming that conclusion. Thanks for validating it.
Reply all
Reply to author
Forward
0 new messages