【发布时间】:2016-04-15 21:39:04
【问题描述】:
我正在使用 Asp.net MVC 4 和 Jcrop jQuery 插件来裁剪图像,裁剪后,我将裁剪后的图像上传到我的服务器。图片上传成功,但裁剪区域与客户端选择的不准确。
这是我的代码:
控制器
[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]
});
});
可能我没有得到准确的结果,因为上传时实际图像大小保持不变,并且视图中图像的大小不计算在内。所以选择的裁剪区域坐标实际上取决于真实图像而不是视图中给出的图像。我已经尝试了很多,但找不到任何解决方案来解决这个问题。如何根据视图中图像的大小获得准确的裁剪图像?
更新
根据 Coulton 的建议,我在控制器中添加了这些代码:
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);
标签: jquery asp.net asp.net-mvc image jcrop