Search code examples
jquerywcf-rest

How to display json as image using jquery?


I have a WCF Web service that returns Images as json.

[OperationContract]
        [WebGet(UriTemplate = "Service/GetCarList")]
        public List<CarModel> GetCarList()
        {

            var carList = _db.Cars.ToList();
            var carPhotos = _db.CarPhotoes.ToList();
            return carList.Select(car => new CarModel
            {
                Id = car.CarId,
                Model = car.Model,
                Images = carPhotos.Where(m => m.CarId == car.CarId).Select(m => m.CarPhoto1).ToList()
            }).ToList();
        } 

I have tried it to show in the DOM by the following way

@{
    ViewBag.Title = "Home Page";
}
<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>

<div id="divMyLetterImage"></div>


<script type="text/javascript">

    var getCarUrl = 'http://localhost:62051/Service/GetCarList';

    $(document).ready(function () {

        $.ajax({
            cache: false,
            type: "GET",
            dataType: "json",
            url: getCarUrl,
            success: function (response) {

                var imag = "<img "
                          + "src='" + "data:image/jpg;base64,"
                          + response[0].Images[0] + "'/>";
                $("#divMyLetterImage").replaceWith(imag);
                alert(response[0].Images[0]);
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });

    });
</script>

response[0].Images[0] returns me

255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,236,0,17,68,117,99,10‌​7,121,0,1,0,4,0,0,0,60,0,0,255,219,0,67,0,2,1,1,2,1,1,2,2,2,2,2,2,2,2,3,5,3,3,3,3‌​,3,6,4,4,3,5,7,6,7,7,7,6,7,7,8,9,11,9,8,8,10,8,7,7,10,13,10,10,11,12,12,12,12, and more

But it is not Working........ How can I do it??


Solution

  • I believe that your line:

    Images = carPhotos.Where(m => m.CarId == car.CarId).Select(m => m.CarPhoto1).ToList()
    

    is wrong and you should return base64 encoded strings. Clearly (according to your comment) you obtain by calling .ToList() a list of numbers representing particular bytes but you need to return Base64 encoded string. The method Convert.ToBase64String may be useful for this purpose.