public void FormatPicture(HttpPostedFileBase file) { WebImage image = new WebImage(file.InputStream); if (image.Width > 85 || image.Height > 85) { int w = image.Width; int h = image.Height; if (w > h) { w = 85; h = image.Height * w / image.Width; } else { h = 85; w = image.Width * h / image.Height; } image.Resize(w, h); } image.Save(PictureFilepath); }The HttpPostedFileBase file comes from the view model and contains the uploaded image from the file control. In this example the image is resized to a maximum of 85 pixels, with the smaller dimension interpolated, and stored.
10 March 2014
MVC - Resize an image
It turns out there is a helper class in the System.Web namespace for treating images. This class, WebImage, makes things like resizing e.g. a user profile picture when it is uploaded very easy:
MVC - Download a file from an action
It is often usefull for files to be downloaded through code, and not directly. In the case of MVC, the download would go via an action. In the following example I download a users profile picture that way, while the actual file is not accessible directly:
[Authorize] public ActionResult Picture() { if (App.GetCurrentUser().HasPicture) { //Finds out if the current user has a picture in App_Data/UserPictures. io.FileStream stream = io.File.OpenRead(App.GetCurrentUser().PictureFilepath); byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); stream.Close(); stream.Dispose(); return File(data, MediaTypeNames.Application.Octet, App.GetCurrentUser() + ".jpg"); } else { return null; } }The file is read into memory and the streamed back as an action result of type File. This principle also allows for files to be generated on the fly without them ever being stored on disc.
Subscribe to:
Posts (Atom)