How to resize thumbnails generated by Uploadfy? ASP.NET C # MVC 4

5

Hello, I would like to know how to resize the thumbnails generated by the jQuery Uploadfy plugins. As I show in the print below, it generates the thumbnails according to the actual size of the images, is it a good practice to only resize them in the sample or resize the file itself?

    
asked by anonymous 17.03.2014 / 15:21

1 answer

4

Ideally you would generate a thumbnail file in addition to the original upload, which will save data. At the time of loading the image, you can load a smaller file, which opens faster, and uses the original file only when needed.

Use the NuGet ImageResizer plugin:

  

link

Example usage:

Model

public class ProductPicture
{
    [Key]
    public int ProductPictureID { get; set; }
    public int ProductID { get; set; }

    [Required]
    public String FileName { get; set; }
    public String Thumbnail { get; set; }

    public virtual Product Product { get; set; }

    [NotMapped]
    public HttpPostedFileBase File { get; set; }

    public ProductPicture() { }

    public ProductPicture(int _ProductID) {
        this.ProductID = _ProductID;
    }
}

Controller

[HttpPost]
public ActionResult Create(ProductPicture productpicture)
{
    // Original Image
    if (productpicture.File != null && productpicture.File.ContentLength > 0)
    {
        // extract only the fielname
        var fileName = Path.GetFileName(productpicture.File.FileName);

        var path = Path.Combine(Server.MapPath(imagesDirectory), fileName);
        productpicture.File.SaveAs(path);
        productpicture.FileName = fileName;
        ModelState.Remove("FileName");

        // Thumbnails
        if (productpicture.File.ContentLength > 0)
        {
                //The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
                //Destination paths can have variables like <guid> and <ext>, or 
                //even a santizied version of the original filename, like <filename:A-Za-z0-9>
            ImageResizer.ImageJob i = new ImageResizer.ImageJob(productpicture.File, 
                imagesDirectory + "/Thumbnails/<guid>.<ext>", new ImageResizer.ResizeSettings(
                                        "width=250;height=250;format=jpg;mode=pad"));
            i.CreateParentDirectory = true; //Auto-create the uploads directory.
            i.Build();
            productpicture.Thumbnail = i.FinalPath.Split('\').Last();
        }
    }

    if (ModelState.IsValid)
    {
        context.ProductPictures.Add(productpicture);
        context.SaveChanges();
        return RedirectToAction("Index");  
    }
}
    
17.03.2014 / 16:22