界面一:

<link href="../theme/js/layui.layim/src/css/layui.css" rel="stylesheet"/>
<style>
#form1 { padding: 10px; }
.usericon { margin-left: 0; }
</style> <form class="layui-form" id="form1" runat="server">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">上传图片</label>
<div class="layui-input-block">
<button id="btnUpload" class="layui-btn" type="button">上传</button>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-block usericon">
<img id="imgShow" src="../theme/img/user.jpg" onerror="../theme/img/user.jpg" width="150" height="150" />
</div>
</div>
</div>
</form>

页面布局代码

<script src="../theme/js/layui.layim/src/layui.js"></script>
<script src="../theme/js/jquery.min.js"></script>
<script type="text/javascript">
layui.use(['layer'], function () {
//上传
$("#btnUpload").on("click", function () {
layer.open({
title: ['上传', 'font-size:18px;'],
area: ['700px', '550px'],
fixed: false, //不固定
maxmin: true,
type: 2,
content: "/test/PreviewImg.aspx"
});
});
});
function Update(src) {
$("#imgShow").attr("src", src);
}
</script>

加入js脚本-点击上传弹出页面进行头像上传和截图,完成后调用Update方法刷新页面

界面二:

<link href="../theme/js/layui.layim/src/css/layui.css" rel="stylesheet" />
<link href="../theme/js/Jcrop/css/jquery.Jcrop.min.css" rel="stylesheet" />
<style>
.container { margin-right: auto; margin-left: auto; *zoom: 1; }
.container:before,
.container:after { display: table; content: ""; line-height: 0; }
.container:after { clear: both; }
.row { *zoom: 1; }
.row:before,
.row:after { display: table; content: ""; line-height: 0; }
.row:after { clear: both; }
.span12 { margin-left: 10px; margin-right: 10px; }
.span12 .layui-btn{margin-left:10px;}
.jc-demo-box { text-align: left; margin: 2em auto; background: white; border: 1px #bbb solid; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); -moz-box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); padding: 1em 2em 2em; }
form { margin: 1.5em 0; }
.jcrop-holder #preview-pane { display: block; position: absolute; z-index: 2000; top: 10px; right: -280px; padding: 6px; border: 1px rgba(0,0,0,.4) solid; background-color: white; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); }
#preview-pane .preview-container { width: 250px; height: 250px; overflow: hidden; }
</style> <form id="form1" runat="server">
<div class="container">
<div class="row">
<div class="span12">
<div class="jc-demo-box">
<img src="../theme/img/user.jpg" id="target" alt="[Jcrop Example]" />
<div id="preview-pane">
<div class="preview-container">
<img src="../theme/img/user.jpg" class="jcrop-preview" alt="Preview" />
</div>
</div>
</div>
<button id="btnUpload" class="layui-btn" type="button">上传</button>
<button id="btnOk" class="layui-btn layui-btn-disabled" type="button">确定</button>
<button id="btnX" class="layui-btn" type="button">0</button>
<button id="btnY" class="layui-btn" type="button">0</button>
<button id="btnW" class="layui-btn" type="button">0</button>
<button id="btnH" class="layui-btn" type="button">0</button>
</div>
</div>
</div>
<asp:HiddenField ID="x1" runat="server" />
<asp:HiddenField ID="y1" runat="server" />
<asp:HiddenField ID="w" runat="server" />
<asp:HiddenField ID="h" runat="server" />
</form>

页面布局代码

<script src="../theme/js/jquery.min.js"></script>
<script src="../theme/js/Jcrop/js/jquery.Jcrop.min.js"></script>
<script src="../theme/js/layui.layim/src/layui.js"></script>
jQuery(function ($) {
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
//console.log('init', [xsize, ysize]);
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: xsize / ysize
}, function () {
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
$('#x1').val(c.x);//左顶点的x坐标
$('#y1').val(c.y);//右顶点的x坐标
$('#w').val(c.w);//截图的宽度
$('#h').val(c.h);//截图的高度
$('#btnX').html(c.x);//左顶点的x坐标
$('#btnY').html(c.y);//右顶点的x坐标
$('#btnW').html(c.w);//截图的宽度
$('#btnH').html(c.h);//截图的高度
};
});

js裁剪的脚本

//上传文件
layui.use('upload', function () {
var upload = layui.upload;
//单个文件上传
var uploadInst = upload.render({
elem: '#btnUpload' //绑定元素
, url: '/test/ashx/ashx.ashx' //上传接口
, data: {
action: "uploadimg"
//, maxSize: $(".jcrop-holder>.jcrop-tracker").width()
}
, before: function (obj) {//在 choose 回调之后、done/error 回调之前触发
//layer.load(); //上传loading
}
, done: function (res) {
//上传完毕回调
$("#target").attr("src", res.data.src);
$(".jcrop-holder>img").attr("src", res.data.src);
$(".preview-container>img.jcrop-preview").attr("src", res.data.src);
$(".jcrop-tracker").siblings("img").attr("src", res.data.src);
//上传图片后-确定按钮可用
$("#btnOk").removeClass("layui-btn-disabled"); }
, error: function () {
//请求异常回调
}
});
});

上传文件

//确定
$("#btnOk").on("click", function () {
if (!$(this).hasClass("layui-btn-disabled")) {
var x= $('#x1').val();//左顶点的x坐标
var y = $('#y1').val();//右顶点的x坐标
var w = $('#w').val();//截图的宽度
var h = $('#h').val();//截图的高度
$.ajax({
//提交数据的类型 POST GET
type: "POST",
//提交的网址
url: '/test/ashx/ashx.ashx',
//提交的数据
data: {
action: "cutimg",
x: x,
y: y,
w: w,
h: h,
src: $("#target").attr("src"),
maxWidth: $(".jcrop-holder>.jcrop-tracker").width(),
maxHeight: $(".jcrop-holder>.jcrop-tracker").height()
},
//返回数据的格式-"xml", "html", "script", "json", "jsonp", "text".
datatype: "json",
//成功返回之后调用的函数
success: function (data) {
if (data.code == 0) {
parent.Update(data.src);
CloseThis();
}
},
//调用出错执行的函数
error: function () {
//请求出错处理
}
});
}
});
//关闭当前iframe
function CloseThis() {
//先得到当前iframe层的索引
var index = parent.layer.getFrameIndex(window.name);
parent.layer.close(index); //再执行关闭
}

确定

/// <summary>
/// 上传图片(如果没有传入宽高,不压缩图片)
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string Uploadimg(HttpContext context)
{
int maxSize = ;//压缩后的最大尺寸(长或高,单位px)
int.TryParse(context.Request.Params["maxSize"], out maxSize);
//图片保存路径
string savePath = "/uploadfiles/test/" + DateTime.Now.ToString("yyyyMM") + "/";
if (!Directory.Exists(context.Server.MapPath(savePath)))
{
Directory.CreateDirectory(context.Server.MapPath(savePath));
}
string fileName = Guid.NewGuid().ToString("N");
HttpPostedFile file = context.Request.Files[];//上传的图片
if (file != null)
{//上传的图片不为空
string fileExt = Path.GetExtension(file.FileName);//文件扩展名
fileName += fileExt;
//压缩后的图片
Bitmap img = FileExt.ImageZip(file.InputStream, fileExt, maxSize);
if (img != null)
{//压缩后的图片不为空
img.Save(context.Server.MapPath(savePath + fileName));
}
else
{//原图片保存
file.SaveAs(context.Server.MapPath(savePath + fileName));
}
}
return "{\"code\":0,\"msg\":\"上传成功\",\"data\":{\"src\":\"" + (savePath + fileName) + "\"}}";
}

执行后台代码-上传文件

/// <summary>
/// 裁剪图片-返回裁剪后的图片地址
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string CutImg(HttpContext context)
{
string src = context.Request.Params["src"];//原图片地址
Image file = Image.FromFile(context.Server.MapPath(src));//上传的图片
int x = string.IsNullOrEmpty(context.Request.Params["x"]) ? : int.Parse(context.Request.Params["x"]);//左顶点的x坐标
int y = string.IsNullOrEmpty(context.Request.Params["y"]) ? : int.Parse(context.Request.Params["y"]);//右顶点的x坐标
int w = string.IsNullOrEmpty(context.Request.Params["w"]) ? : int.Parse(context.Request.Params["w"]);//截图的宽度
int h = string.IsNullOrEmpty(context.Request.Params["h"]) ? : int.Parse(context.Request.Params["h"]);//截图的高度
int maxWidth = string.IsNullOrEmpty(context.Request.Params["maxWidth"]) ? : int.Parse(context.Request.Params["maxWidth"]);//最大宽
int maxHeight = string.IsNullOrEmpty(context.Request.Params["maxHeight"]) ? : int.Parse(context.Request.Params["maxHeight"]);//最大高 string fileExt = Path.GetExtension(src);//图片格式
string fileName = Guid.NewGuid().ToString("N") + fileExt;
string savePath = "/uploadfiles/test/" + DateTime.Now.ToString("yyyyMM") + "/" + fileName; CutImage(GetReducedImage(file, maxHeight, maxHeight), x, y, w, h, savePath, context);
return "{\"code\":0,\"src\":\"" + savePath + "\"}";
} /// <summary>
/// 生成缩略图重载方法1,返回缩略图的Image对象
/// </summary>
/// <param name="Width">缩略图的宽度</param>
/// <param name="Height">缩略图的高度</param>
/// <returns>缩略图的Image对象</returns>
public Bitmap GetReducedImage(Image ResourceImage, int Width, int Height)
{
try
{
//用指定的大小和格式初始化Bitmap类的新实例
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
//从指定的Image对象创建新Graphics对象
Graphics graphics = Graphics.FromImage(bitmap);
//清除整个绘图面并以透明背景色填充
graphics.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片对象
graphics.DrawImage(ResourceImage, new Rectangle(, , Width, Height));
return bitmap;
}
catch (Exception e)
{
return null;
}
} /// <summary>
/// 截取图片方法
/// </summary>
/// <param name="bitmap">原图</param>
/// <param name="beginX">开始位置-X</param>
/// <param name="beginY">开始位置-Y</param>
/// <param name="width">截取宽度</param>
/// <param name="height">截取长度</param>
/// <param name="path">保存路径</param>
/// <param name="context">上下文</param>
public static void CutImage(Bitmap bitmap, int beginX, int beginY, int width, int height, string path, HttpContext context)
{
if (beginX + width > bitmap.Width)
beginX = bitmap.Width - width;
if (beginY + height > bitmap.Height)
beginY = bitmap.Height - height;
Bitmap destBitmap = new Bitmap(width, height);//目标图
Rectangle destRect = new Rectangle(, , width, height);//矩形容器
Rectangle srcRect = new Rectangle(beginX, beginY, width, height);
Graphics g = Graphics.FromImage(destBitmap);
g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
destBitmap.Save(context.Server.MapPath(path), ImageFormat.Jpeg);
}

点击确定-后台进行截图

PC端-上传头像并裁剪的更多相关文章

  1. 移动端 上传头像 并裁剪功能(h5)

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  2. html5 上传头像的裁剪

    本示例使用HTML5 canvas,简单的编写了上传头像的裁剪效果,移动端支持拖拽后裁剪, 虽然样式不好看,但是功能还算全: 下图为裁剪后的效果: html部分: <!DOCTYPE html& ...

  3. WebAPI实现移动端上传头像接口

    测试时可以直接使用PostMan模拟发送请求 /// <summary> /// 手机端上传头像接口 /// </summary> /// <param name=&qu ...

  4. Jcrop+uploadify+php实现上传头像预览裁剪

    最近由于项目需要,所以做了一个上传头像预览并且可以预览裁剪的功能,大概思路是上传的图片先保存到服务器,然后通过ajax从服务器获取到图片信息,再利用Jcrop插件进行裁剪,之后通过PHP获取到的四个裁 ...

  5. ASP.NET MVC在服务端把异步上传的图片裁剪成不同尺寸分别保存,并设置上传目录的尺寸限制

    我曾经试过使用JSAjaxFileUploader插件来把文件.照片以异步的方式上传,就像"MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件01- ...

  6. asp.net实现图片在线上传并在线裁剪

    1.说明 接上一篇文章uploadify实现多附件上传完成后,又突然用到头像上传并在线裁剪.在网上找个众多例子都没有符合要求的,有一篇文章写的不错,就是文旺老兄写的这篇Asp.Net平台下的图片在线裁 ...

  7. 上传头像,界面无跳转,php+js

    上传头像,界面无跳转的方式很多,我用的是加个iframe那种.下面直接上代码. html: //route 为后端接口//upload/avatar 为上传的头像的保存地址//imgurl=/uplo ...

  8. php实现手机拍照上传头像功能

    现在手机拍照很火,那么如何使用手机拍照并上传头像呢?原因很简单,就是数据传递,首先手机传递照片信息,这个就不是post传递 也不是get函数传递, 这个另外一种数据格式传递,使用的是$GLOBALS ...

  9. Android基础之——startActivityForResult启动界面并返回数据,上传头像

    在android应用的开发过程中,常常会出现启动一个界面后填写部分内容后带着数据返回启动前的界面,最典型的应用就是登录过程.在非常多应用程序的模块中,都有"我的"这个模块,在未登录 ...

随机推荐

  1. Java多线程——不变性与安全发布

    1.不变性 某个对象在被创建后其状态就不能被修改,那么这个对象就称为不可变对象,不可变对象一定是线程安全的.不可变对象很简单.他们只有一种状态,并且该状态由构造函数来控制. 当满足以下条件时,对象才是 ...

  2. C#-WebForm-Repeater的灵活运用、ItemCommand的用法-增删改查、如何不适用Repeater来展示数据?

    浏览器页面: 代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Defau ...

  3. 认识CSS中精灵技术(sprite)和滑动门

    前端之HTML,CSS(十) 精灵技术与精灵图 精灵技术本质 精灵技术是一种处理网页背景图像的方式,实质是将小的背景图片拼接到一张大的背景图像上.拼接成的大图被称为精灵图.浏览器打开网页时,每一个图片 ...

  4. [问题解决]Fresco设置圆角效果不生效问题探究

    [问题解决]Fresco设置圆角效果不生效问题探究 /** * Created by diql on 2017/2/21 11:07:04. */ 问题 在View中设置: fresco:rounde ...

  5. np.random.random()函数 参数用法以及numpy.random系列函数大全

    原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/9751471.html 1.np.random.random()函数参数 np.random.r ...

  6. JavaScript数据结构-8.双向链表

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  7. linux mint 19 与windows时间不同步

    首先确定时间无误 sudo apt-get install ntpdate sudo ntpdate time.windows.com 2 sudo hwclock --localtime --sys ...

  8. css定位问题的记录

    postion:relative是子块级元素面向父级元素的相对定位,定位关键字使用left/right/top/bottom.兄弟块元素之间相对进行定位,但是position移动后,原位置依然保留.而 ...

  9. python2和python3中列表推导式的变量泄露问题

    Python 2.x 中,在列表推导中 for 关键词之后的赋值操作可能会影响列表推导上下文中的同名变量.像下面这个 Python 2.7 控制台对话: Python 2.7.15 (default, ...

  10. Django获取Header中的信息

    今天需要从header中获取一些信息,查了一些资料,需要注意一下几点: request.META.get("header key") 用于获取header的信息 注意的是heade ...