我使用asp.net mvc 4
和Jcrop Jquery Plugin
裁剪圖像,裁剪後我將裁剪後的圖像上傳到我的服務器。圖像上傳成功,但裁剪區域與客戶端選擇的內容不一致。這裏是我的代碼,Jcrop未在asp.net中正確裁剪圖像mvc
控制器
[HttpPost]
public ActionResult AdminProfilePic(HttpPostedFileBase file, int Top, int Left, int Bottom, int Right)
{
if (file != null)
{
string picName = User.Identity.Name;
WebImage img = new WebImage(file.InputStream);
string picExt = Path.GetExtension(file.FileName);
if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg" || picExt == ".png")
{
picExt = "PNG";
string path = System.IO.Path.Combine(Server.MapPath("~/Images/Owners/"), picName);
var img_cropped = img.Crop(Top, Left, Bottom, Right).Resize(160, 200, false, true);
img_cropped.Save(path, picExt);
img.Save(path, picExt);
TempData["pp_success"] = "Your profile picture has been updated successfully!";
return RedirectToAction("AdminProfilePic");
}
else
{
TempData["pp_fail"] = "Error! Please upload a valid image file only!";
return RedirectToAction("AdminProfilePic");
}
}
else
{
TempData["pp_fail"] = "Error! No File was selected!";
return RedirectToAction("AdminProfilePic");
}
}
查看
@using (Html.BeginForm("AdminProfilePic", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file01" style="width: 100%;" /><br />
<img id="blah01" style="height: 350px;" class="img-responsive" src="#" alt="your image" /><div id="cropper"></div>
@Html.TextBox("Top", null, new { id = "Top" })<br />
@Html.TextBox("Left", null, new { id = "Left" })<br />
@Html.TextBox("Bottom", null, new { id = "Bottom" })<br />
@Html.TextBox("Right", null, new { id = "Right" })<br />
<input type="submit" class="btn btn-success" value="Update Profile Picture" />
}
JS
$(document).ready(function() {
function showCoords(c) {
$("#Top").val(c.x);
$("#Left").val(c.y);
$("#Bottom").val(c.x2);
$("#Right").val(c.y2);
}
$('#blah01').Jcrop({
onSelect: showCoords,
bgColor: 'black',
bgOpacity: .4,
maxSize: [160, 200]
});
});
也許我ñ不能得到準確的結果,因爲上傳時實際圖像大小保持不變,並且視圖中圖像的大小將不計入。因此,選定的裁剪區域座標實際上取決於實際圖像,而不是視圖中給出的圖像。我嘗試了很多,但找不到解決此問題的任何解決方案。如何根據視圖中圖像的大小獲取準確的裁剪圖像?嚴重需要這個幫助!謝謝。
UPDATE
按庫爾頓的建議,我在我的控制器中添加這些代碼,
var myW = img.Width;
var myH = img.Height;
var Top = y;
var Left = x;
var Bottom = myH - y2;
var Right = myW - x2;
var img_cropped = img.Crop(Top, Left, Bottom, Right).Resize(160, 200, false, true);
截圖
左邊是上傳後的更新圖像,並且右側是種植部分。
我分配'x'到'top',你正在傳遞'y'到.....'$(「#Top」)。val(c.y);' – Luke