user2862542
user2862542

Reputation: 205

How to use ImageResizer in C# .NET/MVC4

I'm working on a site where I need to crop and resize images that people upload. I got the code for the upload function but in my httpPost action result I want to resize the image to start off with. I also got the code for that but I can't find a way to show the image.

Here is my code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
    if (uploadFile.ContentLength > 0)
    {
        foreach (string fileKey in System.Web.HttpContext.Current.Request.Files.Keys)
        {
            HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[fileKey];
            if (file.ContentLength <= 0) continue; //Skip unused file controls.

            ImageResizer.ImageJob i = new ImageResizer.ImageJob(file, "~/img/", new ImageResizer.ResizeSettings("width=50;height=50;format=jpg;mode=max"));

            i.CreateParentDirectory = true; //Auto-create the uploads directory.
            i.Build();

            string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
            string physicalPath = Server.MapPath(relativePath);
            uploadFile.SaveAs(physicalPath);

            return View((object)relativePath);

    }
}

I want go write out the Image information from ImageResizer.ImageJob i.. Any ideas? Thank you!

Upvotes: 1

Views: 4912

Answers (1)

Lilith River
Lilith River

Reputation: 16468

First, the code you're using allows anybody to upload an executable page and run it.

Never, under any circumstances, should you use uploadFile.FileName as part of the final path name, unless you deeply understand path and length sanitization.

Second, ImageJob needs a destination path, not a folder path. You can use variables, like "~/img/<guid>.<ext>" and access the resulting physical path from i.FinalPath. You can use ImageResizer.Util.PathUtils.GuessVirtualPath(i.FinalPath) to get the app-relative path.

As this is almost a precise duplicate of mvc3 ImageResizer, please consider using the search feature before posting.

Upvotes: 2

Related Questions