Hi jmontano,
Check this example. Now please take its reference and correct your code.
Namespaces
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Save()
{
string filePath = Path.Combine(this.Environment.WebRootPath, "Images", "Cropped.png");
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
ViewBag.OriginalImage = Request.Form["hfImage"].ToString();
byte[] bytes = Convert.FromBase64String(Request.Form["hfImage"].ToString().Split(',')[1]);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
Image image = Image.FromFile(filePath);
using (Image thumbnail = image.GetThumbnailImage(200, 200, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
using (MemoryStream memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png);
byte[] bytes = new byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, (int)bytes.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
ViewBag.ResizedImage = "data:image/png;base64," + base64String;
}
}
return View("Index");
}
public bool ThumbnailCallback()
{
return false;
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Save">
<input type="file" id="FileUpload1" />
<input type="submit" id="btnUpload" value="Upload" />
<input type="hidden" name="hfImage" id="hfImage" />
<hr />
<table>
<tr>
<th>Original</th>
<th>Resized</th>
</tr>
<tr>
<td><img id="Image1" src="@ViewBag.OriginalImage" alt="" height="250" width="250" /></td>
<td><img id="Image1" src="@ViewBag.ResizedImage" alt="" height="200" width="200" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#FileUpload1').change(function () {
var reader = new FileReader();
reader.onload = function (e) {
$('#hfImage').val(e.target.result);
}
reader.readAsDataURL($(this)[0].files[0]);
});
});
</script>
</body>
</html>
Screenshot