The ideal would be to generate a thumbnail file beyond the original upload, in which there will be data saving. When uploading the image, you can upload a smaller file, which opens faster, and use the original file only when needed.
Use the Nuget Imageresizer plugin:
https://www.nuget.org/packages/ImageResizer/
Example of use:
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");
}
}
This code resizes the image completely, doesn’t it? I wanted to know a way to just resize it when it finishes uploading. Because when it finishes, they stay the original size and the form below will stop far away from there hehe
– Luiz Negrini
Notice that I put up a field called
Thumbnail
in theModel
. It is another file smaller than the original, and it is this file that should be displayed.– Leonel Sanches da Silva
Yes I saw this part, however, still it is not what I want, because I want to keep the original size of the image, only show on the upload screen (after it fills the bar it shows the image, when it uploads) with a size different from the original.
– Luiz Negrini
So, but it’s all there. Where is
// Original Image
is the logic that saves the original image.// Thumbnails
is the logic that generates the miniature.– Leonel Sanches da Silva
Yes but without this model it already generates a thumbnail (only it is the normal image hehe)... understand?
– Luiz Negrini
Let me improve the answer.
– Leonel Sanches da Silva