Home return image byte array in an action of mvc controller and display image in javascript
Reply: 1

return image byte array in an action of mvc controller and display image in javascript

sadori
1#
sadori Published in 2018-02-14 04:47:11Z

In MVC, We are going to get image from server and display it in client, GetImage Action in controller is as follows:

public byte[] GetImage()
{
    byte[] imgByteArray=File.ReadAllBytes("Img1.jpeg");
    return imgByteArray  ;          
}

And javascript code in client side is as follows:

$.ajax(
...
  success: function (response) {
                $('#imgResult')
                 .attr('src', 'data:image/jpeg;base64,' + response);
           },
    error: function (er) {
                        alert(er);
          }

The response is received successfully but image is not displayed and src value is set to:

src="data:image/jpeg;base64,System.Byte[]"

How can resolve this issue?

Ray
2#
Ray Reply to 2018-02-14 06:02:45Z

Tested and working code:

Controller :

    [HttpGet]
    public JsonResult GetImage()
    {
        System.Drawing.Image img = 
        System.Drawing.Image.FromFile(@"D:\yourimagepath.PNG");
        byte[] bytes;
        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            bytes = ms.ToArray();
        }

        return Json(new { base64imgage = Convert.ToBase64String(bytes) }
          , JsonRequestBehavior.AllowGet);
    }

Ajax call :

  $.ajax({
        .....

      success: function (data) {

            var imag = "<img "
            + "src='" + "data:image/png;base64,"
            + data.base64imgage + "'/>";

            $("#imgResult").html(imag);

            //here imgResult is Div id and inside img is getting created.

        }

        });
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342957 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO