MVC4 de Image Upload, Crop (Kırpma) İşlemleri

Merhaba Arkadaşlar;

Image upload işlemini aslında kendeio, jequery upload, mvc nin içinde helper metodları kullanarak yapılabilir. Çok geniş ve yyöntemleri farklı ve oldukça zor bir konudur. Ben ce iyi bir javascript koduyla mükemmel bir iş çıkartalıbilir. Bu yadığım kod daha da geliştirilebilir. 

Crop işlemi için gerekli kütüphaneyi buradan indiriyoruz.

Ayrııca display template  ve editor template konularında bilgi sahibi olmamız gerekiyor. Burada Bayram Üçüncü konuyu iyi açıklamış..

Öncelikle Upload işlemi kodlarını yazılım...

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

Daha Sonra displaytemplate için resim.cshtml dosyasını yazlım..Bu dosya shared/DisplayTemplate klasörününü anltında olması gerekir.

@model System.String

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




şimdide index.cshtml yazalım..

@using FileUpload.Controllers;
@model ProfileViewModel

@using Microsoft.Web.Helpers;
<h2>Index</h2>

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { @encType = "multipart/form-data" }))
{
    @Html.DisplayFor(x => x.ImageUrl)<br/>
    @FileUpload.GetHtml(initialNumberOfFiles:1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: "Add Files", uploadText: "Upload File")<br />   
<input type="submit" name="submit" text="upload" />
}

Ben burada microsoftun web helper kulladınm package id si "microsoft-web-helpers" şeklindedir. Bunu muget consoleyi kullanarak indiriebilirsiniz. Bu FileUpload

 heplerı ile birden fazla resim eklenebilmekte. Şimdi upload işlemini yapacak Actionımızı yazalım...

private bool CreateFolderIfNeeded(string path)
            {
                bool result = true;
                if (!Directory.Exists(path))
                {
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch (Exception)
                    {
                        /*TODO: You must process this exception.*/
                        result = false;
                    }
                }
                return result;
            }

            public ActionResult Upload(ProfileViewModel model)
            {
                var image = WebImage.GetImageFromRequest();
                if (image != null)
                {
                    if (image.Width > 500)
                    {
                        image.Resize(500, ((500 * image.Height) / image.Width));
                    }
                    var filename = Path.GetFileName(image.FileName);

                    if (this.CreateFolderIfNeeded(Server.MapPath("~/Temp")))
                    {
                        try
                        {
                            image.Save(Path.Combine("../Temp", filename));
                            filename = Path.Combine("~/Temp", filename);
                            model.ImageUrl = Url.Content(filename);

                        }
                        catch (Exception ex)
                        {
                            string message = string.Format("File upload failed: {0}", ex.Message);
                        }
                    }

                }
                return View("Index", model);
            }
        }

 

 

 

Bir  crop işelemi client tarafında sadece seçim işlemini yaptırıyoruz. Crop işlemini ise servere yaptırdığımız için crop kordinatları için gerekli bir model yazalım..

public class EditorInputModel
        {
            public ProfileViewModel Profile { get; set; }
            public double Top { get; set; }
            public double Bottom { get; set; }
            public double Left { get; set; }
            public double Right { get; set; }
            public double Width { get; set; }
            public double Height { get; set; }
        }

Şimdi de crop işlemi için gerekli kodlarımız yazalım.  Upload Action methodumuzu tekrardan düzenleyerek aşağıdaki kodları ekleyelim

//return View("Index", model);
                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);

Daha sonra editor.cshtml doasyasını ve gerekli script kodları yazalım..

@using FileUpload.Controllers;
@model EditorInputModel

@section Head{

  <link href="~/Content/Jcrop-v0.9.12/css/jquery.Jcrop.css" rel="stylesheet" />
        <script src="~/Scripts/jquery-1.8.2.js"></script>
       <script src="~/Content/Jcrop-v0.9.12/js/jquery.Jcrop.min.js"></script> 
    }

<h2>Editor</h2>
<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='Crop' />
}
</div>
<script>
  
    $(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'
    });
}
}


Daha sonra crop işleminin yapacak actionımızı yapalım..

[HttpPost]
            public ActionResult Edit(EditorInputModel editor)
            {
                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;

                if (this.CreateFolderIfNeeded(Server.MapPath("~/ProfileImage")))
                {
                    try
                    {
                        editor.Profile.ImageUrl = Url.Content("~/ProfileImage/" + Path.GetFileName(image.FileName));
                        image.Resize(100, 100, true, false);
                        image.Save(@"~" + editor.Profile.ImageUrl);
                    }
                    catch (Exception ex)
                    {
                        string message = string.Format("File upload failed: {0}", ex.Message);
                    }
                } 
                
                System.IO.File.Delete(Server.MapPath(originalFile));
                return View("Index", editor.Profile);
            }

 

 

 

Projenini tümünü burdan indiriebilirsiniz..

 

FileUploadAndCrop.rar (11,55 mb)

Add comment

The file '/Custom/Widgets/Calendar/widget.cshtml' does not exist.The file '/Custom/Widgets/Category list/widget.cshtml' does not exist.The file '/Custom/Widgets/Tag cloud/widget.cshtml' does not exist.The file '/Custom/Widgets/Page List/widget.cshtml' does not exist.The file '/Custom/Widgets/Month List/widget.cshtml' does not exist.