截图上传功能 imageAreaselect

前台:

<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<link href="~/Scripts/MyJsLibrary/css/imgareaselect-default.css" rel="stylesheet" />
<script src="~/Scripts/MyJsLibrary/jquery.imgareaselect.min.js"></script>
<script src="~/Scripts/FileUpload/js/ajaxfileupload.js"></script>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$('img#imgselect').imgAreaSelect({
selectionColor: 'blue',
x1: 20, y1: 10, x2: 120, y2: 110,
maxWidth: 100, maxHeitht: 100,
minWidth: 100, minHeight: 100,
selectionOpacity: 0.1,
handles: true,
aspectRatio: '1:1',
onSelectEnd: preview
});
})
function preview(img, selection) {
if (selection.width > 49) {
//getValue(selection);
var defultWidth = $("img#imgselect").width();
var defultHeight = $("img#imgselect").height();
console.info("width:" + defultWidth + "Height:" + defultHeight);
var scaleX = 200 / (selection.width || 1);
var scaleY = 200 / (selection.height || 1);//200px的框
var scaleX1 = 100 / (selection.width || 1);
var scaleY1 = 100 / (selection.height || 1);//100px的框
//获取上传图片的默认width,Height
$('#preview200').css({
width: Math.round(scaleX * defultWidth) + 'px',//先把图片缩小想要的框的大小,比如200的大小
height: Math.round(scaleY * defultHeight) + 'px',//然后在把图片放大图片的大小。
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
$('#preview100').css({
width: Math.round(scaleX1 * defultWidth) + 'px',
height: Math.round(scaleY1 * defultHeight) + 'px',
marginLeft: '-' + Math.round(scaleX1 * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY1 * selection.y1) + 'px'
});
$("#x1").val(Math.round(selection.x1));
$("#x2").val(Math.round(selection.x2 - selection.x1));//截取得宽度
$("#y1").val(Math.round(selection.y1));
$("#y2").val(Math.round(selection.y2 - selection.y1));//截取得高度
}
}

/**检查图片上传类型*/
function checkImgType(obj) {
var imgFile = '';
//获取图片的全路径
var imgFilePath = getImgFullPath(obj);
var endIndex = imgFilePath.lastIndexOf('\\');
var lastIndex = imgFilePath.length - endIndex - 1;
if (endIndex != -1)
imgFile = imgFilePath.substr(endIndex + 1, lastIndex);
else
imgFile = imgFilePath;
var tag = true;
endIndex = imgFilePath.lastIndexOf('.');
if (endIndex == -1)
tag = false;
var ImgName = imgFilePath.substr(endIndex + 1, lastIndex);
ImgName = ImgName.toUpperCase();
if (ImgName != 'JPEG' && ImgName != 'JPG' && ImgName != 'PNG' && ImgName != 'BMP') {
tag = false;
}
if (!tag) {
alert('上传图片的文件类型必须为: *.JPEG,*.jpg,*.png,*.bmp,请重新选择!')
alert('你逗我么');
// Upload.clear(obj);
return false;
}
return true;
}
function getImgFullPath(obj) {
if (obj) {
//ie
if (window.navigator.userAgent.indexOf('MSIE') >= 1) {
obj.select();
return document.selection.createRange().text;
}
//firefox
else if (window.navigator.userAgent.indexOf('Firefox') >= 1) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
}
return obj.value;
}
}
});
//立即显示图片
//下面用于图片上传预览功能
function setImagePreview() {
var docObj = document.getElementById("file1");
var imgObjPreview = document.getElementById("imgselect");
if (docObj.files && docObj.files[0]) {
//火狐下,直接设img属性
imgObjPreview.style.display = 'block';
//imgObjPreview.style.width = '300px'; //不能控制大小
//imgObjPreview.style.height = '300px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
var srcStirng = window.URL.createObjectURL(docObj.files[0]);
$("#src").val(srcStirng);
$("#preview200").attr("src", srcStirng);
$("#preview100").attr("src", srcStirng);
}
else {
//IE下,使用滤镜
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//必须设置初始大小
localImagId.style.width = "150px";
localImagId.style.height = "180px";
//图片异常的捕捉,防止用户修改后缀来伪造图片
try {
localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch (e) {
alert("您上传的图片格式不正确,请重新选择!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}


$(function () {
//一点激上传开始上传
$("#upload").click(function () {
// 获取文件路径
var filePath = $("#file1").val();
console.info(filePath);
// 获取“.”位置
//var extStart = filePath.lastIndexOf(".");
//// 获取文件格式后缀,并全部大写
//var ext = filePath.substring(extStart, filePath.length).toUpperCase();

//// 判断文件格式
//if (ext != ".BMP" && ext != ".PNG" && ext != ".JPG" && ext != ".JPEG") {
// alert("图片仅限于.BMP .PNG .JPG .JPEG文件。");
// return false;
//}
//else {


// 使用ajaxfileupload上传文件
$.ajaxFileUpload({
url: "SaveImg",
secureuri: false,
fileElementId: 'file1',
dataType: 'JSON',
data: { fileType: filePath },
success: function (data) {
// $("#src").val(data);
//$("#upload").submit();开始截图
////获取坐标并传值
var x1=$("#x1").val();
var x2=$("#x2").val();//截取得宽度
var y1=$("#y1").val();
var y2=$("#y2").val();//截取得高度
console.info(x1+x2+y1+y2);

$.ajax({
url: "imgEditHandler",
type: "Post",
data: { xx1: x1, xx2: x2, yy1: y1, yy2: y2 },
success: function (data) {
if (data.success==true) {
alert("上传成功");
}
}
});
},
error:
function (data, status, e) {
//alert(data + "," + status + "," + e);
alert("上传失败");
}
});
});
});
</script>
<style type='text/css'>
#container
{
position: absolute;
left: 40px;
background: #FFF;
border: #666 2px solid;
border-radius: 10px;
width: 600px;
height: 500px;
padding: 20px;
}

#selectdiv
{
width: 350px;
height: 550px;
float: left;
}

#uploaddiv
{
margin-top: 20px;
border-top: #CCC 1px solid;
}

#prediv200
{
height: 200px;
width: 200px;
overflow: hidden;
border: #CCC 3px dashed;
}

#prediv100
{
height: 100px;
width: 100px;
overflow: hidden;
border: #CCC 3px dashed;
}

#preview
{
position: relative;
overflow: hidden;
}

[type=button]
{
width: 50px;
}
</style>
</head>
<body>
<div>
<div id='container'>
<div id='selectdiv'>
<div id="localImag">
<img id="imgselect" style="border: 1px solid #f00;" alt=""
src="Images/t01.jpg" />
</div>
<div>
<p>图片上传:<font color='red'>*.BMP *.PNG *.JPG *.JPEG</font></p>
@* @using (Html.BeginForm("imgEditHandler", "EditUploadImg", FormMethod.Post, new { Area = "TestFunction" }))
{
<input type='file' name='imgFile' id='imgFile'><br />
*@<input type='text' name='x1' id="x1" value='0' />
<input type='text' name='y1' id="y1" value='0' />
<input type='text' name='x2' id="x2" value='0' />
<input type='text' name='y2' id="y2" value='0' /><br />
<input type="text" name="src" id="src" value="" />
<input type="file" id="file1" name="uploadImageFile" onchange="setImagePreview();" />
<input type="button" value='上传' id='upload' />
@*}*@
</div>
</div>
<div id='prediv200'>
<img id='preview200' src='~/Content/UploadImg/fdsfsdfsdfsd.jpg' width='200px' height='200px' />
</div>
<div id='prediv100'>
<img id='preview100' src='~/Content/UploadImg/fdsfsdfsdfsd.jpg' width='100px' height='100px' />
</div>
<div>
<form>
@* <input type='hidden' name='x1' value='0' />
<input type='hidden' name='y1' value='0' />
<input type='hidden' name='width' value='100' />
<input type='hidden' name='height' value='100' />
<br />
<br />*@
<input type='button' value='修改' id='button2' />
</form>
</div>
@if (ViewData["success"] != null)
{
<script type="text/javascript">
$(function () {
$(".success").slideDown();
$("#ok").slideUp();
});
</script>
<div style="display: none;position:absolute;top:200px;left:200px;z-index:1000;" class="success">
上传成功
<input type="button" id="ok" value="确定" />
</div>
}
else
{
<span>上传失败</span>
}
</div>
</div>
</body>
</html>

 

后台:

public ActionResult SaveImg(HttpPostedFileBase uploadImageFile)
{
//保存上传图片
// 随机数
string img = uploadImageFile.FileName;
int index = img.IndexOf('.');
string[] fileName = img.Split('.');
var rand = new Random().Next(0, 8999);
// 创建文件存放的文件路径,如果没有,创建该路径
string tempImg = "~/Content/UploadImg/";//路径模板
string folder = HttpContext.Server.MapPath(tempImg);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
// 保存全文件路径
string filePath = Path.Combine(folder, fileName[0] + rand + "." + fileName[1]);

//写cookie
//HttpContext.Response.Cookies["srcImg"].Value = filePath;
HttpCookie cookies = new HttpCookie("srcImg");
cookies.Value = HttpUtility.UrlEncode(filePath, Encoding.GetEncoding("UTF-8")); ;
cookies.Expires = DateTime.Now.AddHours(1);
HttpContext.Response.Cookies.Add(cookies);
uploadImageFile.SaveAs(filePath);
//return Json(new { success=true,pathsrc=filePath});
return Content(filePath);
//保存成功
}
/// <summary>
/// 截取
/// </summary>
/// <param name="forms"></param>
/// <returns></returns>
public ActionResult imgEditHandler(int xx1,int xx2,int yy1,int yy2)
{
string tempImg = "~/Content/UploadImg/";//路径模板
int x1 = Convert.ToInt32(xx1);
int y1 = Convert.ToInt32(yy1);
int x2 = Convert.ToInt32(xx2);//实际上是没有用的
int y2 = Convert.ToInt32(yy2);//实际上是没有用得
//string srcImg = tempImg + fileName[0] + rand + "." + fileName[1];//原图图片存在路径
//string srcImg = form["src"];
//到cookie 拿路径
//string srcImg = Common.DEncrypt.DEncrypt.Decrypt(HttpContext.Request.Cookies["srcImg"].Value);
string srcImg = HttpUtility.UrlDecode(Common.CommonClass.GetCookie("srcImg"), Encoding.GetEncoding("UTF-8")); ; ;
//string srcPath = HttpContext.Server.MapPath(srcImg);//实际路径
//创建图象,保存将来截取的图象
//Bitmap image = new Bitmap(Path);
//Graphics imgGraphics = Graphics.FromImage(image);
//设置截屏区域
//imgGraphics.CopyFromScreen(x1, y1, x2, y2, new Size(100, 100));
//保存
//SaveImage(image);
string[] fileName = srcImg.Split('.');
//string file = fileName[0]+fileName[1] + "caijinhao." + fileName[2];
string folders = HttpContext.Server.MapPath("~/Content/UploadImg/");//映射路径
string newpath = CutImage(srcImg, x1, y1, x2, y2, Guid.NewGuid().ToString("N"), folders, fileName[fileName.Length - 1]);
ViewData["success"] = "true";
return View("img3");
}
/// <summary>
/// 截取图片方法
/// </summary>
/// <param name="url">图片地址</param>
/// <param name="beginX">开始位置-X</param>
/// <param name="beginY">开始位置-Y</param>
/// <param name="getX">截取宽度</param>
/// <param name="getY">截取长度</param>
/// <param name="fileName">文件名称</param>
/// <param name="savePath">保存路径</param>
/// <param name="fileExt">后缀名</param>
public string CutImage(string url, int beginX, int beginY, int getX, int getY, string fileName, string savePath, string fileExt)
{
//if ((beginX < getX) && (beginY < getY))
//{
Bitmap bitmap = new Bitmap(url);//原图
//if (((beginX + getX) <= bitmap.Width) && ((beginY + getY) <= bitmap.Height))
//{
// Bitmap destBitmap = new Bitmap(getX, getY);//目标图 创建新图大小
Bitmap destBitmap = new Bitmap(100, 100);//要存储的图像的大小
Rectangle destRect = new Rectangle(0, 0, getX, getY);//我要在新图的开始画图的位置
Rectangle srcRect = new Rectangle(beginX, beginY, getX, getY);//我要在原图的这个位置复制
Graphics imgGraphics = Graphics.FromImage(destBitmap);
imgGraphics.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
ImageFormat format = ImageFormat.Png;
switch (fileExt.ToLower())
{
case "png": format = ImageFormat.Png; break;
case "bmp": format = ImageFormat.Bmp; break;
case "gif": format = ImageFormat.Gif; break;
}
destBitmap.Save(savePath + "//" + fileName + "." + fileExt, format);
return savePath + "\\" + "*" + fileName.Split('.')[0] + "." + fileExt;
//}
//else
//{ return "截取范围超出图片范围"; }
//}
//else
//{ return "请确认(beginX < getX)&&(beginY < getY)"; }
}

posted @ 2015-06-23 10:52  caijinhao  阅读(452)  评论(0编辑  收藏  举报