Pages

Thursday, June 13, 2013

Resize and save an image which uploaded using file upload control in c#

Here is the code for controller class.

public class FileUploadController : Controller
{
    //
    // GET: /FileUpload/

    public ActionResult Index()
    {
        return View();
    }
    public ActionResult FileUpload()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        WebImage img = new WebImage(file.InputStream);
        if (img.Width > 1000)
            img.Resize(1000, 1000);
        img.Save("path");
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FileUpload(HttpPostedFileBase uploadFile)
    {
        if (uploadFile.ContentLength > 0)
        {
            string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
            string physicalPath = Server.MapPath(relativePath);


            FileUploadModel.ResizeAndSave(relativePath, uploadFile.FileName, uploadFile.InputStream, uploadFile.ContentLength, true);

            return View((object)relativePath);
        }
        return View();
    }
}

Here is the code for model class

public class FileUploadModel
{
    [Required]
    public HttpPostedFileWrapper ImageUploaded { get; set; }

    public static void ResizeAndSave(string savePath, string fileName, Stream imageBuffer, int maxSideSize, bool makeItSquare)
    {
        int newWidth;
        int newHeight;
        Image image = Image.FromStream(imageBuffer);
        int oldWidth = image.Width;
        int oldHeight = image.Height;
        Bitmap newImage;
        if (makeItSquare)
        {
            int smallerSide = oldWidth >= oldHeight ? oldHeight : oldWidth;
            double coeficient = maxSideSize / (double)smallerSide;
            newWidth = Convert.ToInt32(coeficient * oldWidth);
            newHeight = Convert.ToInt32(coeficient * oldHeight);
            Bitmap tempImage = new Bitmap(image, newWidth, newHeight);
            int cropX = (newWidth - maxSideSize) / 2;
            int cropY = (newHeight - maxSideSize) / 2;
            newImage = new Bitmap(maxSideSize, maxSideSize);
            Graphics tempGraphic = Graphics.FromImage(newImage);
            tempGraphic.SmoothingMode = SmoothingMode.AntiAlias;
            tempGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            tempGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            tempGraphic.DrawImage(tempImage, new Rectangle(0, 0, maxSideSize, maxSideSize), cropX, cropY, maxSideSize, maxSideSize, GraphicsUnit.Pixel);
        }
        else
        {
            int maxSide = oldWidth >= oldHeight ? oldWidth : oldHeight;

            if (maxSide > maxSideSize)
            {
                double coeficient = maxSideSize / (double)maxSide;
                newWidth = Convert.ToInt32(coeficient * oldWidth);
                newHeight = Convert.ToInt32(coeficient * oldHeight);
            }
            else
            {
                newWidth = oldWidth;
                newHeight = oldHeight;
            }
            newImage = new Bitmap(image, newWidth, newHeight);
        }
        newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
        image.Dispose();
        newImage.Dispose();
    }
}

Also this code supports the crop, flip, watermark operation etc.

Wednesday, June 12, 2013

Upload a image and display on same page in asp.net mvc4

Once you save the uploaded file on the server from your controller action you could pass back the url to this file to the view so that it can be displayed in an <img> tag:

public class FileUploadController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult FileUpload()
    {
        return View();
    }
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FileUpload(HttpPostedFileBase uploadFile)
    {
        if (uploadFile.ContentLength > 0)
        {
            string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
            string physicalPath = Server.MapPath(relativePath);
            uploadFile.SaveAs(physicalPath);
            return View((object)relativePath);
        }
        return View();
    }

}

Then make your view strongly typed and add an <img> tag that will display the image if the model is not empty:

@model string
<h2>FileUpload</h2>

@using (Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })
{
    <input name="uploadFile" type="file" />
    <input type="submit" value="Upload File" />
}

@if (!string.IsNullOrEmpty(Model))
{
    <img src="@Url.Content(Model)" alt="" />
}