Click here to Skip to main content
Click here to Skip to main content

Upload, Rename Image, and Resize (MVC)

, 21 Oct 2012
Rate this:
Please Sign up or sign in to vote.
How to upload, rename and resize in MVC

Introduction

View.cshtml

 @using (Html.BeginForm("Action","Controller",FormMethod.Post, new {enctype = "multipart/form-data"} ) )
{
    <div>Upload Image</div>           
    <input type="file" name="avatar" />    
    <input type="submit" value="upload" />    
}

Calling the function from the controller:

foreach (string item in Request.Files)
{
    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
    if (file.ContentLength == 0)
        continue;
        
    if (file.ContentLength > 0)
    {   
        //the function will validate the extension, upload the image 
        // rename the image if it exists on the server
        //  and resize the image 
        HelperFunctions.renameUploadFile(file);
    }
}

HelperFunctions.cs

// folder for the upload
public static readonly string ItemUploadFolderPath = "~/Images/Items/";

        public static bool renameUploadFile(HttpPostedFileBase file,Int32 counter = 0)
        {
            var fileName =  Path.GetFileName(file.FileName);

            string append = "item_";
            string finalFileName = append+((counter).ToString())+"_"+fileName;
            if (System.IO.File.Exists
        (HttpContext.Current.Request.MapPath(ItemUploadFolderPath + finalFileName)))
            {
                //file exists 
                return renameUploadFile(file, ++counter);
            }
            //file doesn't exist, upload item but validate first
            return uploadFile(file,finalFileName);
        }

        private static bool uploadFile(HttpPostedFileBase file, string fileName)
        {
            var path = 
          Path.Combine(HttpContext.Current.Request.MapPath(ItemUploadFolderPath), fileName);
            string extension = Path.GetExtension(file.FileName);

            //make sure the file is valid
            if (!validateExtension(extension))
            {
                return false;
            }

            try
            {
                file.SaveAs(path);

                Image imgOriginal = Image.FromFile(path);

                //pass in whatever value you want 
                Image imgActual = ScaleBySize(imgOriginal, 600);
                imgOriginal.Dispose();
                imgActual.Save(path);
                imgActual.Dispose();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private static bool validateExtension(string extension)
        {
            extension = extension.ToLower();
            switch (extension)
            {
                case ".jpg":
                    return true;
                case ".png":
                    return true;
                case ".gif":
                    return true;
                case ".jpeg":
                    return true;
                default:
                    return false;
            }
        }

        public static Image ScaleBySize(Image imgPhoto, int size)
        {
            int logoSize = size;

            float sourceWidth = imgPhoto.Width;
            float sourceHeight = imgPhoto.Height;
            float destHeight = 0;
            float destWidth = 0;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            // Resize Image to have the height = logoSize/2 or width = logoSize.
            // Height is greater than width, set Height = logoSize and resize width accordingly
            if (sourceWidth > (2 * sourceHeight))
            {
                destWidth = logoSize;
                destHeight = (float)(sourceHeight * logoSize / sourceWidth);
            }
            else
            {
                int h = logoSize / 2;
                destHeight = h;
                destWidth = (float)(sourceWidth * h / sourceHeight);
            }
            // Width is greater than height, set Width = logoSize and resize height accordingly

            Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
                                        PixelFormat.Format32bppPArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
                new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();

            return bmPhoto;
        } 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

rtp4
Web Developer Multi-Sens
Lebanon Lebanon
I have been web developing for about 2 years now.
Am currently working at Multi-Sens.
Before that I worked as a Php developer.

Comments and Discussions

 
QuestionThanks for your help ... Pinmemberamir_arsalan_k21-Jul-14 2:45 
GeneralMy vote of 2 Pinmemberz.tanvir8-Jan-14 0:51 
GeneralMy vote of 1 Pinmemberchepurichandrakanth@gmail.com22-Jan-13 23:01 
GeneralMy vote of 5 PinmemberSavalia Manoj M22-Oct-12 20:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 21 Oct 2012
Article Copyright 2012 by rtp4
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid