Reputation: 85
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?
Upvotes: 0
Views: 1848
Reputation: 188
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.
}
});
Upvotes: 1