Hi rani,
Check this example. Now please take its reference and correct your code.
Install the ImageProcessor.Core.CoreCompat from nuget package.
Namespaces
using System.Drawing;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
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 Index(IFormFile postedFile)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
else
{
Directory.Delete(path, true);
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(postedFile.FileName);
string file = Path.Combine(path, fileName);
using (FileStream stream = new FileStream(file, FileMode.Create))
{
postedFile.CopyTo(stream);
}
Image img = Image.FromFile(file);
int x = (img.Width / 4);
int y = (img.Height / 4);
int width = (img.Height / 4) * 2;
int height = (img.Height / 4) * 2;
Rectangle cropRect = new Rectangle(x, y, width, height);
Bitmap destination = new Bitmap(cropRect.Width, cropRect.Height);
using (Graphics graphics = Graphics.FromImage(destination))
{
graphics.DrawImage(Image.FromFile(file),
new Rectangle(0, 0, destination.Width, destination.Height), cropRect, GraphicsUnit.Pixel);
}
destination.Save(Path.Combine(path, "Cropped_" + fileName));
ViewBag.File = "Uploads/Cropped_" + fileName;
return View();
}
}
View
@{
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="Index">
<span>Select File:</span>
<input type="file" name="postedFile" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
Screenshot