简体   繁体   中英

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

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?

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.

        }

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM