MVC uses JCrop to upload and crop images

Source: Internet
Author: User

JCrop is used to crop images. What you want to experience in this article is:

 

Upload images on the view page:


Upload successful. Go to another edit view page, crop the image using JCrop, and save the image to the specified folder:


After the cropping is successful, the cropping image is displayed on the main view page:


Of course, the most likely practice in an actual project is to upload, crop, and save on this page.

 

□Ideas

→ On the Upload Image view page, Upload and save the image to a temporary folder, Upload
→ On the edit cropping view page, click "crop" to set parameters that can be provided by JCrop, such as width, height, distance from top, and distance from bottom, encapsulate the distance from the left and right into a class and pass it to the Controller method.
→ The Controller Method crops the Image Based on the received parameters, saves the image to the target folder ProfileImages, and deletes the corresponding image in the Temporary Folder Upload.

 

To upload the main View page of an image, you need a View Model corresponding to it, which contains the attributes of the image path. This image path attribute is not a simple field display and editing. When the View Model of the main View page is transferred to the image editing and cropping View pages, based on the characteristics of jscdrop, there must be cropping and previewing areas for images. Therefore, we need to use the UIHint feature for the path attribute of the View Model on the main View page to customize display and edit views for this attribute. The View Model on the main View page is:

using System.ComponentModel.DataAnnotations;namespace MvcApplication1.Models{    public class ProfileViewModel    {        [UIHint("ProfileImage")]        public string ImageUrl { get; set; }    }}

 

On the image editing and cropping View pages, the corresponding View Model not only has the View Model of the main View page as its attributes, but also has attributes related to JCrop. These attributes do not need to be displayed, it only needs to exist in the form of hidden fields. Through the JCrop event, the JCrop parameter is assigned to these hidden fields. The corresponding View Model is:

using System.Web.Mvc;namespace MvcApplication1.Models{    public class EditorInputModel    {        public ProfileViewModel Profile { get; set; }        [HiddenInput]        public double Top { get; set; }        [HiddenInput]        public double Bottom { get; set; }        [HiddenInput]        public double Left { get; set; }        [HiddenInput]        public double Right { get; set; }        [HiddenInput]        public double Width { get; set; }        [HiddenInput]        public double Height { get; set; }     }}

 

On the main view page of the uploaded image, you must introduce Microsoft. Web. Helpers (via NuGet) and use the FileUpload in the namespace to generate the upload element.

@ Using Microsoft. Web. Helpers @ model MvcApplication1.Models. ProfileViewModel @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Index 

 

In HomeController:

The action method Upload is used to receive the View Model from the main View, save the image to the Temporary Folder Upload, and assign the View Model of the main View to edit and crop the attributes of the View Model in the View.

 

You also need to introduce the System. Web. Helpers component, which is the WebImage class and provides some APIs for uploading images.

 

The action side Edit receives the View Model from the editing and cropping views. Based on the parameters, use the WebImage API to crop the images, save the images to the target folder ProfileImages, and delete the related images in the Temporary Folder Upload.

Using System. web. mvc; using MvcApplication1.Models; using System. web. helpers; using System. IO; namespace MvcApplication1.Controllers {public class HomeController: Controller {public ActionResult Index () {return View ();} // if the image is uploaded successfully, go to the cropping page, that is, the editing page [HttpPost] public ActionResult Upload (ProfileViewModel model) {var image = WebImage. getImageFromRequest (); // System must be referenced. web. helpers assembly if (image! = Null) {// limit that the image length cannot exceed 500 pixels if (image. width> 500) {image. resize (500, (500 * image. height)/image. width);} // obtain the relative Path var filename = Path based on the image name. getFileName (image. fileName); // Save the image to the specified folder image. save (Path. combine ("~ /Upload/", filename); // obtain the absolute Path of the image filename = Path. combine (".. /Upload/", filename); model. imageUrl = Url. content (filename); var editModel = new EditorInputModel () {Profile = model, Width = image. width, Height = image. height, Top = image. height * 0.1, Left = image. width * 0.9, Right = image. width * 0.9, Bottom = image. height * 0.9}; return View ("Editor", editModel);} return View ("Index", model );} // Cropping page editing page [HttpPost] public ActionResult Edit (EditorInputModel editor) {// var image = new WebImage ("~ /"+ Editor. profile. imageUrl); var image = new WebImage (editor. profile. imageUrl); var height = image. height; var width = image. width; image. crop (int) editor. top, (int) editor. left, (int) (height-editor. bottom), (int) (width-editor. right); var originalFile = editor. profile. imageUrl; // the original image path editor. profile. imageUrl = Url. content ("~ /ProfileImages/"+ Path. GetFileName (image. FileName); image. Resize (100,100, true, false); image. Save (@"~ "+ Editor. profile. imageUrl); System. IO. file. delete (Server. mapPath (originalFile); // Delete the uploaded image in Upload. return View ("Index", editor. profile );}}}


On the edit or crop view page, you must reference the css and js files corresponding to Jcrop.
@ Model MvcApplication1.Models. EditorInputModel @ {ViewBag. Title = "Editor"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Editor 

 

Since the [UIHint ("ProfileImage")] feature is applied to the ImageUrl of the main View Model, this means that the corresponding custom View must exist.

public class ProfileViewModel    {        [UIHint("ProfileImage")]        public string ImageUrl { get; set; }    }

 

Views/Home/EditorTemplates/ProfileImage. cshtml:

@model System.String<div id="cropContainer">    <div id="cropPreview">            </div>    <div id="cropDisplay">            </div></div>


Views/Home/DisplayTemplates/ProfileImage. cshtml is a custom display template for the ImageUrl attribute:

@model System.String

References:
Http://blog.tallan.com/2011/02/04/using-mvc3-razor-helpers-and-jcrop-to-upload-and-crop-images/
Http://www.schnieds.com/2011/07/image-upload-crop-and-resize-with.html
Http://zootfroot.blogspot.com/2010/12/mvc-file-upload-using-uploadify-with.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.