0

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?

1 Answer 1

1

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.

        }

        });
Sign up to request clarification or add additional context in comments.

1 Comment

,Thank you so much, great solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.