溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ASP.NET?MVC如何使用JCrop上傳并裁剪圖片

發(fā)布時(shí)間:2022-08-01 11:05:57 來源:億速云 閱讀:130 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“ASP.NET MVC如何使用JCrop上傳并裁剪圖片”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

在視圖頁(yè)上傳圖片:

ASP.NET?MVC如何使用JCrop上傳并裁剪圖片

上傳成功,跳轉(zhuǎn)到另外一個(gè)編輯視圖頁(yè),使用JCrop對(duì)該圖片裁剪,并保存圖片到指定文件夾:

ASP.NET?MVC如何使用JCrop上傳并裁剪圖片

裁剪成功后,在主視圖頁(yè)顯示裁剪圖片:

ASP.NET?MVC如何使用JCrop上傳并裁剪圖片

當(dāng)然,實(shí)際項(xiàng)目中最有可能的做法是:在本頁(yè)上傳、裁剪并保存。

思路

  • 在上傳圖片視圖頁(yè),把圖片上傳保存到一個(gè)臨時(shí)文件夾Upload

  • 在編輯裁剪視圖頁(yè),點(diǎn)擊"裁剪"按鈕,把JCrop能提供的參數(shù),比如寬度、高度、離頂部距離,離底部距離,離左右端距離等封裝成類,傳遞給控制器方法

  • 控制器方法根據(jù)接收到的參數(shù),對(duì)圖片裁剪,把圖片保存到目標(biāo)文件夾ProfileImages,并刪除掉臨時(shí)文件夾Upload里對(duì)應(yīng)的圖片。

為了配合上傳圖片的主視圖頁(yè),需要一個(gè)與之對(duì)應(yīng)的View Model,其中包含圖片路徑的屬性。而這個(gè)圖片路徑屬性不是簡(jiǎn)單的字段顯示編輯,當(dāng)主視圖頁(yè)的View Model被傳遞到圖片編輯、裁剪視圖頁(yè)后,根據(jù)JScrop特點(diǎn),肯定有針對(duì)圖片的裁剪和預(yù)覽區(qū)域,所以,我們需要針對(duì)主視圖頁(yè)View Model的路徑屬性使用UIHint特性,為該屬性定制顯示和編輯視圖。主視圖頁(yè)的View Model為:

using System.ComponentModel.DataAnnotations;

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

在圖片編輯、裁剪視圖頁(yè),對(duì)應(yīng)的View Model不僅有主視圖頁(yè)的View Model作為它的屬性,還有與JCrop相關(guān)的屬性,這些屬性無需顯示,只需要以隱藏域的方式存在著,通過JCrop的事件,把JCrop參數(shù)賦值給這些隱藏域。對(duì)應(yīng)的View Model為:

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; } 
    }
}

在上傳圖片的主視圖頁(yè)中,需要引入Microsoft.Web.Helpers(通過NuGet),使用該命名空間下的FileUpload幫我們生成上傳元素。

@using Microsoft.Web.Helpers
@model MvcApplication1.Models.ProfileViewModel


@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Index</h3>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new {@encType = "multipart/form-data"}))
{
    @Html.DisplayFor(x => x.ImageUrl)<br/>
    @FileUpload.GetHtml(initialNumberOfFiles:1,includeFormTag:false, uploadText:"上傳圖片")<br/>
    <input type="submit" name="submit" text="上傳" />
}

在HomeController中:

action方法Upload用來接收來自主視圖的View Model,把圖片保存到臨時(shí)文件夾Upload中,并把主視圖的View Model賦值給編輯、裁剪視圖中View Model的屬性。

還需要引入System.Web.Helpers組件,該組件WebImage類,提供了針對(duì)上傳圖片處理的一些API。

action方Edit接收來自編輯、裁剪視圖中View Model,根據(jù)參數(shù),使用WebImage類的API對(duì)圖片裁剪,保存到目標(biāo)文件夾ProfileImages,并刪除臨時(shí)文件夾Upload中的相關(guān)圖片。

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();
        }

        //如果圖片上傳成功就到裁剪頁(yè)、即編輯頁(yè)
        [HttpPost]
        public ActionResult Upload(ProfileViewModel model)
        {
            var image = WebImage.GetImageFromRequest(); //必須引用System.Web.Helpers程序集
            if (image != null)
            {
                //限制圖片的長(zhǎng)度不能大于500像素
                if (image.Width > 500)
                {
                    image.Resize(500, ((500*image.Height)/image.Width));
                }

                //根據(jù)圖片的名稱獲取相對(duì)路徑
                var filename = Path.GetFileName(image.FileName);
                //保存圖片到指定文件夾
                image.Save(Path.Combine("~/Upload/", filename));

                //獲取圖片的絕對(duì)路徑
                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);
        }

        //裁剪頁(yè) 編輯頁(yè)
        [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;//圖片原路徑

            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)); //把在Upload中的上傳圖片刪除掉
            return View("Index", editor.Profile);
        }
         
    }
}

在編輯、裁剪視圖頁(yè),需要引用Jcrop對(duì)應(yīng)的css和js文件。

@model MvcApplication1.Models.EditorInputModel

@{
    ViewBag.Title = "Editor";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Editor</h3>
<link href="~/Content/jquery.Jcrop.css" rel="external nofollow"  rel="stylesheet" />


<div id="mainform">
    @using (Html.BeginForm("Edit", "Home", FormMethod.Post))
    {
        @Html.EditorFor(x => x.Profile.ImageUrl)
        @Html.HiddenFor(x => x.Left)
        @Html.HiddenFor(x => x.Right)
        @Html.HiddenFor(x => x.Top)
        @Html.HiddenFor(x => x.Bottom)
        @Html.HiddenFor(x => x.Profile.ImageUrl)
        <input type="submit" name="action" value="裁剪"/>
    }
</div>

@section scripts
{
    <script src="~/Scripts/jquery.Jcrop.js"></script>
    <script type="text/javascript">
        $(function() {
            $('#profileImageEditor').Jcrop({
                onChange: showPreview,
                onSelect: showPreview,
                setSelect: [@Model.Top, @Model.Left, @Model.Right, @Model.Bottom],
                aspectRatio: 1
            });
        });

        function showPreview(coords) {
            if (parseInt(coords.w) > 0) {
                $('#Top').val(coords.y);
                $('#Left').val(coords.x);
                $('#Bottom').val(coords.y2);
                $('#Right').val(coords.x2);

                var width = @Model.Width;
                var height = @Model.Height;
                var rx = 100 / coords.w;
                var ry = 100 / coords.h;

                $('#preview').css({
                    width: Math.round(rx * width) + 'px',
                    height: Math.round(ry * height) + 'px',
                    marginLeft: '-' + Math.round(rx * coords.x) + 'px',
                    marginTop: '-' + Math.round(ry * coords.y) + 'px'
                });
            }
            
        }
    </script>
}

既然為主視圖View Model的ImageUrl打上了[UIHint("ProfileImage")]特性,這意味著必須有對(duì)應(yīng)的自定義強(qiáng)類型視圖。

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

Views/Home/EditorTemplates/ProfileImage.cshtml,是針對(duì)ImageUrl屬性的自定義編輯模版:

@model System.String
<div id="cropContainer">
    <div id="cropPreview">
        <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="preview" />
    </div>
    <div id="cropDisplay">
        <img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImageEditor" />
    </div>
</div>

Views/Home/DisplayTemplates/ProfileImage.cshtml,是針對(duì)ImageUrl屬性的自定義顯示模版:

@model System.String

<img src="@(String.IsNullOrEmpty(Model) ? "" : Model)" id="profileImage" />

“ASP.NET MVC如何使用JCrop上傳并裁剪圖片”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI