Configure RouteConfig:
public
class
RouteConfig
{
public
static
void
RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name:
"Default",
url:
"{controller}/{action}/{id}",
defaults:
new
{ controller = "Image",
action = "Index",
id = UrlParameter.Optional
}
);
}
}
Add Controller:
using
System;
using
System.IO;
using
System.Web.Mvc;
namespace
Base64Img.Controllers
{
public
class
ImageController
: Controller
{
//
GET: Image
public
ActionResult
Index()
{
return
View();
}
[HttpGet]
public
ActionResult
GetBase64Image()
{
string
path = "D:\\IMG_152236552973901.jpeg";
FileStream
fileStream = new
FileStream(path,
FileMode.Open,
FileAccess.Read);
byte[]
data = new
byte[(int)fileStream.Length];
fileStream.Read(data,
0, data.Length);
return
Json(new
{ base64imgage = Convert.ToBase64String(data)
}
,
JsonRequestBehavior.AllowGet);
}
}
}
Associate a view to this Controller (ImageController)
@{
Layout
= null;
}
<!DOCTYPE
html>
<html>
<head>
<meta
name="viewport"
content="width=device-width"
/>
<title>Loading
base64 Image</title>
<script
src="~/Scripts/jquery-1.10.2.min.js"></script>
<script
language="javascript"
type="text/javascript">
var
imageUrl = "GetBase64Image";
var
imgs = null;
$(document).ready(function
() {
var
displayImage = function
(base64Data) {
var
imag = "<img
"
+
"src='"
+ "data:image/jpg;base64,"
+
base64Data + "'/>";
$("#dvImageHolder").html(imag)
};
$("#btLoadImage").click(function
() {
if
(imgs != null)
{
displayImage(imgs.base64imgage);
return;
}
$.ajax({
cache:
false,
type:
"GET",
url:
imageUrl,
contentType:
'application/json',
dataType:
"json",
success:
function
(data) {
imgs
= data;
displayImage(imgs.base64imgage);
},
error:
function
(xhr) {
alert("Error
occurred while loading the image. "
+
xhr.responseText);
}
});
});
$("#btClearImage").click(function
() {
$("#dvImageHolder").html("");
});
});
</script>
</head>
<body>
<div
id="dvImageHolder"></div>
<div>
<button
id="btClearImage">
Clear
Image
</button>
<button
id="btLoadImage">
Load
Image
</button>
</div>
</body>
</html>
Cheers!!