Image Resize in Asp .Net Core. | Asp.Net Core 3.1 | Discover Vibes

 Hello guys, let's learn how to do image resize in Asp.Net Core.

 

Step 1: Let's create Controller class and create its constructor and add "IHostingEnviromnet" interface.

Step 2: Install "System.Drawing.Common" nuget package.

Step 3: Back-end controller logic is in below.

public class ImageController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public ImageController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult ImageResize()
        {
            return View();
        }
        [HttpPost]
        public IActionResult ImageResize(IFormFile file)
        {
            int height = 400;
            int width = 400;
            string path = Path.Combine(_hostingEnvironment.WebRootPath, "Image", "resized.jpg");
            Image image = Image.FromStream(file.OpenReadStream(), true, true);
            var newImage = new Bitmap(width, height);
            using (var a = Graphics.FromImage(newImage))
            {
                a.DrawImage(image, 0, 0, width, height);
                newImage.Save(path);
            }
            return View();
        }
    }

Step 4: Create "Image" folder inside wwwroot folder.


 

Step 5: Create view.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" class="btn btn-primary"/>
    </form>
</body>
</html>

Now run your project and test it.

Thank You

Comments

Popular posts from this blog

How to Generate Script of Database With Data And Without Data