c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
asp.net MVC

How to generate high Quality thumbnail images and maintain aspect ration in asp.net c#

| | ASP-NET , MVC

In this article, I will show you how to compress image size in asp.net c#. The following image resize code provides good resize image keep aspect ratio without losing Quality of the image.

We have to maintain aspect ratio of actual image when working with images in c#, otherwise the thumbnail image will look very bad. Here the following function written in c# code will easily generate high quality thumbnail. We have to pass the actual image path and the thumbnail path i.e where the new generated thumbnail image will be saved.

Step 1:  Create a asp.net mvc application and right click on the "Controllers" folder and add "Home" controller. Copy and paste the following code. Import the namespace System.Drawing and System.Drawing.Imaging.

   public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Index(picture picture)
        {
            foreach (var file in picture.files)
            {
 
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var filePath = Path.Combine(Server.MapPath("~/Images"),fileName);
 
                    var newThumbnail = Path.GetFileName(file.FileName);
                    var ThumbPath = Path.Combine(Server.MapPath("~/Thumbimg"),fileName);
 
                    file.SaveAs(filePath);
                    Guid id = Guid.NewGuid();
 
                    Generate(filePath,ThumbPath, 100, 150);
                }
            }
            TempData["Message"] = "Generated successfully";
            return RedirectToAction("Index");
        }
 
        public static void Generate(string actualImagePath, string thumbnailPath, int thumbWidth, int thumbHeight)
        {
            Image orignalImage = Image.FromFile(actualImagePath);
 
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
            int newHeight = orignalImage.Height * thumbWidth /orignalImage.Width;
            int newWidth = thumbWidth;
 
            if (newHeight > thumbHeight)
            {
                newWidth = orignalImage.Width *thumbHeight / orignalImage.Height;
                newHeight = thumbHeight;
            }
 
            //Generate a thumbnail image
            Image thumbImage = orignalImage.GetThumbnailImage(newWidth,newHeight, null, IntPtr.Zero);
 
            // Saveresized picture
            var qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
            var quality = (long)100; //Image Quality
            var ratio = new EncoderParameter(qualityEncoder, quality);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            //Rightnow I am saving JPEG only you can choose other formats as well
            var codecInfo = GetEncoder(ImageFormat.Jpeg);


            thumbImage.Save(thumbnailPath,codecInfo, codecParams);
 
            //Dispose unnecessory objects
            orignalImage.Dispose();
            thumbImage.Dispose();
        }
 
       
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

 

Step 2: Right click on the HomeControllers and create an index view. Copy and paste the following code.

<style type="text/css">
    .btn {
        width: 100px;
        height: 50px;
        background: #00BCD4;
        border-style: solid;
        border-color: white;
        color: white;
    }
</style>
<div style="border: 1px solid #DED8D8; width: 500px; height: 350px; font-family: Arial; padding-left: 5px">
    @using (@Html.BeginForm(null, null, FormMethod.Post,
     new { enctype = "multipart/form-data" }))
    {
        if (TempData["Message"] != null)
        {
        <p style="font-family: Arial; font-size: 16px; font-weight: 200; color: red">@TempData["Message"]</p>
        }
        <table>
            <tr>
                <td style="padding-bottom: 35px" colspan="2">
                    <h2 style="color: #FF5722">Generate high Quality Thumbnail images</h2>
                </td>
            </tr>
            <tr>
                <td style="width: 100px;">
                    <b style="color: #FF5722">File:</b>
                </td>
                <td>
                    <input type="file" name="files" id="files" multiple="multiple" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td colspan="2" style="padding-top: 30px">
                    <input type="submit" class="btn" name="submit" />
                </td>
            </tr>
        </table>
    }
</div>

Description: Run the application and upload the image that you want to resize. The code written in the controller method Generate has the basic formula to maintain aspect ratio of thumbnail image height and width and generate high Quality thumbnail image and saved as JPEG format in the specified folder.