image retrieving in mvc with web response

Posted by Unknown

image retrieving in mvc with web response

in this blog am going to explain you about image retrieving in mvc with web response.

In order to do i have taken once actin method in controller which will sends you the response in bytes with a web request.

In the view page i have taken image tag and a button.upon a button click i want to call a web request and render the response in to image tag.

In the Controller 

public HttpResponseMessage GetImage()
  {
   HttpResponseMessage response = new HttpResponseMessage();

     TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
   Bitmap bmp = (Bitmap)typeConverter.ConvertFrom(yourImage);

            
   //3
   var Fs = new FileStream(HostingEnvironment.MapPath("~/Images") + @"\I" + Id.ToString() + ".png", FileMode.Create);
   bmp.Save(Fs,ImageFormat.Png);
   bmp.Dispose();

   //4
   Image img = Image.FromStream(Fs);
   Fs.Close();
   Fs.Dispose();

   //5
   MemoryStream ms = new MemoryStream();
   img.Save(ms, ImageFormat.Png);

   //6
   response.Content = new ByteArrayContent(ms.ToArray());
   ms.Close();
   ms.Dispose();
             
   response.Content.Headers.ContentType = new     MediaTypeHeaderValue("image/png");
           response.StatusCode = HttpStatusCode.OK;
            return response;
  }
}
}


In the view Page
<table>
<tr>
  <td>
   <input type="button" id="btngetemp" value="Get Employee" />
  </td>
</tr>
<tr>
  <td>
   <img id="emimage" src="" height="100" width="100"/>
  </td>
</tr>
</table>
Add the following script in the view:
<script type="text/javascript">
$(document).ready(function () {
  $("#btngetemp").click(function () {
 
  $("#emimage").attr("src", "http://localhost:4208/ctrllr/GetImage/");
});
});
</script>


Labels: ,

Post a Comment

 
test