web实现QQ头像上传截取功能
由于最近一段时间比较忙,发现好久没写博客了,给大家分享下最近搞的logo上传截取功能。在实现这个功能之前找了一些jq的插件,最后选定了cropper在github中可以找到。
具体的思路是1:选择上传的图片,在change事件中用form.jquery.js中的formajax异步提交表单,保存上传的图片
2:绑定cooper事件,对图片进行选取。
3:得到选中区域的坐标,对图片进行截取保存。
其中的难点是ie的兼容性问题,由于本人也不是很好,就不献丑了下面给大家附上代码
页面中的html

<div class="input">
<div><span class="xuanze">选择</span><input type="file" class="file" name="file" id="file" onchange="change()" /><span class="jpeg">支持jpg、jpeg、gif、png、bmp格式的图片</span></div>
<div class="xiechneg">
<span class="daxc">
@{
var url = Model.LogoMiddleUrl == null ? "" : Model.LogoMiddleUrl;
var path200 = ReadConfig.GetHostUrl("Host") + url;
}
<img src="@path200" width="118" height="49" alt="" />
</span><i class="dxgou"></i><i class="dxcha"></i><span class="shuzi01">200*80 </span>
<span class="xiaoxc">
@{
var url1 = Model.LogoSmallUrl == null ? "" : Model.LogoSmallUrl;
var path100 = ReadConfig.GetHostUrl("Host") + url1;
}
<img src="@path100" width="95" height="38" alt="" />
</span><i class="xiaoxgou"></i><i class="xiaoxcha"></i><span class="shuzi02">100*40 </span>
</div> <div class="yzhz">
<div class="xiaoyz">
<div class="img-container"> <img src="/Content/img/xtsz/xiaoyizi.jpg" width="400" height="280" alt="" id="HeadPic" />
</div>
<span class="logo">选择本地照片,上传编辑自己的LOGO</span>
<span class="qd" onclick="SubmitHead()">确定</span>
</div>
<div class="ybXC">
<span class="lgyl">LOGO预览</span>
<div class="img-preview preview-lg">
</div>
<div class="img-preview preview-md">
</div> </div>
</div>
</div>

cropper下载地址http://jquery-plugins.net/image-cropper-jquery-image-cropping-plugin
form.jquery.js的下载地址 http://malsup.com/jquery/form/#download
页面的js
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
<script> function change() { var pic = document.getElementById("HeadPic"), file = document.getElementById("file"); var ext = file.value.substring(file.value.lastIndexOf(".") + 1).toLowerCase(); // gif在IE浏览器暂时无法显示 if (ext != 'png' && ext != 'jpg' && ext != 'jpeg') { alert("图片的格式必须为png或者jpg或者jpeg格式!"); return; } var isIE = navigator.userAgent.match(/MSIE/) != null, isIE6 = navigator.userAgent.match(/MSIE 6.0/) != null; if (isIE) { file.select(); file.blur(); var reallocalpath = document.selection.createRange().text; // IE6浏览器设置img的src为本地路径可以直接显示图片 if (isIE6) { pic.src = reallocalpath; } else { //// 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现 //pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='crop',src=\"" + reallocalpath + "\")"; //// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片 //pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; //CutPic(); $("#HeadForm").ajaxSubmit({ type: "POST", url: "/AjaxCommon/UpPic/", dataType: "text", success: function (data) { $("#HeadSrc").val(data); $("#HeadPic").attr("src", "@ReadConfig.GetHostUrl("Host")" + data); CutPic(); } }); } } else { html5Reader(file); } } function html5Reader(file) { var file = file.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { var pic = document.getElementById("HeadPic"); pic.src = this.result; $("#HeadForm").ajaxSubmit({ type: "POST", url: "/AjaxCommon/UpPic/", dataType: "text", success: function (data) { $("#HeadSrc").val(data); CutPic(); } }); CutPic(); }; } function CutPic() { var $image = $('.img-container>img'); var options = { aspectRatio: 5 / 2, preview: '.img-preview', }; $image.cropper(options); } function SubmitHead() { $.NabianPost({ url: "/Handler/CutImage.ashx", data: { filesrc: $("#HeadPic").attr("src"), top: parseInt($(".cropper-move").offset().top - $(".cropper-canvas").offset().top), left: parseInt($(".cropper-move").offset().left - $(".cropper-canvas").offset().left), height: parseInt($(".cropper-move").css("height")), width: parseInt($(".cropper-move").css("width")), HeadSrc: $("#HeadSrc").val() }, callback: function (data) { if (data.status == "no") { alert("对不起上传失败"); } else { alert("上传成功"); window.location.reload(); } } }); } </script> |
上传图片的方法

public ActionResult UpPic()
{
var file = Request.Files["file"];
if (file.ContentLength == 0)
{
return Content("请选择文件");
}
if (file.ContentLength > 307200)
{
return Content("文件过大");
}
int width = 0; int height = 0;
string path = ReadEnum.GetFilePath((int)FilePath.GYS_Logo);
string HostUrl = ReadConfig.GetHostUrl("HostUrl");
string finalPaht;
Request.Files.Processing(HostUrl, path, 400, 280, 100, out finalPaht, "GYS_Logo", 11);
string a = path;
return Content(a);
}

截取并保存截取后的图片的handler
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; using BCommon.common; using BLL.BLL; using Model.Model; namespace www.nabian.com.Handler { /// <summary> /// CutImage 的摘要说明 /// </summary> public class CutImage : IHttpHandler, System.Web.SessionState.IRequiresSessionState { /// <summary> /// 对图像的裁减操作主入口 /// </summary> /// <param name="context">所有HTTP请求的特定信息</param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/json"; string fileSource = context.Request["filesrc"]; //原文件路径和文件名 //文件保存路径 string HostUrl = ReadConfig.GetHostUrl("HostUrl"); //minilogo的保存路径 string path100 = ReadEnum.GetFilePath((int)FilePath.GYS_inLOGO100_40); string path200 = ReadEnum.GetFilePath((int)FilePath.GYS_inLOGO200_80); int cutY = int.Parse(context.Request["top"]); //Y轴坐标 int cutX = int.Parse(context.Request["left"]); //X轴坐标 int cutWidth = int.Parse(context.Request["width"]); //裁减宽度 int cutHeight = int.Parse(context.Request["height"]); //裁减高度 string HeadSrc = HostUrl + context.Request["HeadSrc"]; //裁减后上传 CutImg(HeadSrc, cutX, cutY, cutWidth, cutHeight, path100, "GYS_inLOGO100_40", context); CutImg(HeadSrc, cutX, cutY, cutWidth, cutHeight, path200, "GYS_inLOGO200_80", context); //如果文件存在,说明文件上传成功 if (File.Exists(HostUrl + path100) && File.Exists(HostUrl + path200)) { var user = (B_Com_User)context.Session["LoginUser"]; var com = new B_Com_CompanyBLL().SelectByID(user.CompanyID.ToString()); com.LogoUrl = HeadSrc; com.LogoMiddleUrl = path200; com.LogoSmallUrl = path100; if (new B_Com_CompanyBLL().UpdateLogoById(com)) { context.Response.Write("{\"status\":\"ok\"}"); } else { context.Response.Write("{\"status\":\"no\"}"); } } else { context.Response.Write("{\"status\":\"error\"}"); } } /// <summary> /// 从指定路径中获取图片,按照指定位置及大小截取相应的图片内容,并保存到指定路径下 /// </summary> /// <param name="filepath">图片来源路径及文件名(已使用Server.MapPath)</param> /// <param name="cutX">裁减的起始X轴坐标</param> /// <param name="cutY">裁减的起始Y坐标</param> /// <param name="cutwidth">裁减的宽度</param> /// <param name="cutheight">裁减的高度</param> /// <param name="savepath">裁减后的图片名称,路径为上一级的images文件夹中</param> /// <param name="context">所有http特定的信息对象</param> void CutImg(string filepath, int cutX, int cutY, int cutwidth, int cutheight, string savepath, string fileName, HttpContext context) { //TODO 判断文件类型暂时未做 //创建图像对象,由于web中有个image控件,会导致这个图像的类重复,需要带上使用命名空间 System.Drawing.Image oldImage = System.Drawing.Image.FromFile(filepath); //创建一个指定宽高的图像对象 System.Drawing.Image newImage = new Bitmap(cutwidth, cutheight); //创建存放截取图像的画布 Graphics newGraphics = Graphics.FromImage(newImage); //创建矩形对象,裁减是就是照着这个矩形来裁减的 Rectangle CutReatangle = new Rectangle(cutX, cutY, cutwidth, cutheight); //创建矩形对象,用于下面的指定裁减出来的图像在新画布上的显示情况 Rectangle showRectangle = new Rectangle(0, 0, cutwidth, cutheight); //执行裁减操作 newGraphics.DrawImage(oldImage, showRectangle, CutReatangle, GraphicsUnit.Pixel); //释放资源(除图像对象的资源) oldImage.Dispose(); newGraphics.Dispose(); DateTime time = DateTime.Now; CreateFile.CreateFolder(ReadConfig.GetHostUrl("HostUrl") + ReadConfig.GetHostUrl(fileName) + "\\" + time.Year + "\\" + time.Month + "\\" + time.Day + "\\"); //保存新图到指定路径 //newImage.Save(ReadConfig.GetHostUrl("HostUrl") + savepath, System.Drawing.Imaging.ImageFormat.Jpeg); if (fileName == "GYS_inLOGO100_40") { newImage.ImageWinvarOptions(ReadConfig.GetHostUrl("HostUrl") + savepath, 100, 40, 100); } else { newImage.ImageWinvarOptions(ReadConfig.GetHostUrl("HostUrl") + savepath, 200, 80, 100); } //释放新图像的资源,如果在保存前释放,会造成程序出错 newImage.Dispose(); } /// <summary> /// 判断原始文件后缀是否符合要求规范 /// </summary> /// <param name="filepath">原始文件路径</param> /// <returns>true为符合</returns> bool CheckImageMime(string filepath) { int typeLastShow = filepath.LastIndexOf('.'); string[] imageType = { "jpg", "gif", "png", "bmp" }; for (int i = 0; i < imageType.Length; i++) { //如果有后缀名且后缀符合规范 if (typeLastShow > 0 && imageType[i].Equals(filepath.Substring(typeLastShow + 1), StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// 根据原始文件名返回前面加上操作时间的文件名 /// </summary> /// <param name="filepath">原文件全名(路径+文件名称)</param> /// <returns>新的文件名称</returns> string NewFileName(string filepath) { //获取文件原名 string oldFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1); //获取操作时间,原使用的是yyyyMMddHHmmssffff string date = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString(); //新文件名 string newFileName = date + oldFileName; return newFileName; } public bool IsReusable { get { return false; } } } } |
压缩图片的方法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace BCommon.common
{
public static class ImageWinvar
{
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="img">原图片的文件流</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="dHeight">高度</param>
/// <param name="dWidth"></param>
/// <param name="flag">压缩质量 1-100</param>
/// <returns></returns>
public static bool ImageWinvarOptions(this Image img, string dFile, int dWidth, int dHeight, int flag)
{
ImageFormat tFormat = img.RawFormat;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(img.Width, img.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
{
if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(img, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
img.Dispose();
ob.Dispose();
}
} }
}

web实现QQ头像上传截取功能的更多相关文章
- 【javascript】html5中使用canvas编写头像上传截取功能
[javascript]html5中使用canvas编写头像上传截取功能 本人对canvas很是喜欢,于是想仿照新浪微博头像上传功能(前端使用canvas) 本程序目前在谷歌浏览器和火狐浏览器测试可用 ...
- struts2_文件上传的功能
使用Struts内置的fileUpload拦截器(已默认配置)即可,设计的电商网站,提供用户头像上传的功能 1. 2. 3. 4. 5. 5.未使用拦截器 6.未使用filename 7. 8. 9.
- android头像上传(获取头像加剪切)
因为项目中需要用到头像上传的功能,所以就下个Ddmo先来实现下. demo我是类似仿微信的,在一个GridView中展示所有的图片,其中第一个item可以去照相:获取到图片后再进行剪切. 图片的剪切是 ...
- jquery头像上传剪裁插件cropper的前后台demo
因为一个项目要做一个头像上传的功能,因此选择了使用jquery的头像插件cropper,cropper是一款使用简单且功能强大的图片剪裁jQuery插件,但是在使用的时候,有一个很大的坑需要注意,那就 ...
- Yii2.0 集成使用富头像上传编辑器
在开发过程中,我们会用到头像上传的功能.这里给大家推荐一款比较流行的头像上传组件,FullAvatarEditor 2.3(富头像上传编辑器). 实际效果如图所示: 1.下载组件,下载地址:http: ...
- 【Bootstrap-插件使用】Jcrop+fileinput组合实现头像上传功能
作者:Dreawer链接:https://zhuanlan.zhihu.com/p/24465742来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 作者:梦游的龙猫(转 ...
- [Bootstrap-插件使用]Jcrop+fileinput组合实现头像上传功能
很久没有更新博客了,再不写点东西都烂了. 这次更新一个小内容,是两个插件的组合使用,实现头像上传功能. 业务需求: 头像上传功能,要对上传的文件进行剪切,且保证头像到服务器时必须是正方形的. 优化&l ...
- qt实现头像上传功能
想必大家都使用过qt的自定义头像功能吧,那么图1应该不会陌生,本片文章我就是要模拟一个这样的功能,虽然没有这么强大的效果,但是能够满足一定的需求. 图1 qq上传图片 首先在讲解功能之前,我先给出一片 ...
- 我需要在Web上完成一个图片上传的功能
我需要在Web上完成一个图片上传的功能. 这个页面需要能从手机中选择图片上传. 首先,这个页面是从微信上面触发的,所以修改了微信的的入口地址,增加了身份识别号作为传参. 跳转到页面的时候,页面先检查身 ...
随机推荐
- float right
很多时候,"更多"会和title在一行显示,放在右边 我们可能马上想到这样做: h1 a{ float: right; } <h1>这是个title<a>更 ...
- ElasticSearch 深度分页解决方案 {"index":{"number_of_replicas":0}}
常见深度分页方式 from+size es 默认采用的分页方式是 from+ size 的形式,在深度分页的情况下,这种使用方式效率是非常低的,比如 from = 5000, size=10, es ...
- 【css】绝对定位的元素在 ie6 下不显示
问题描述: 在 ie6 中如果一个浮动元素与绝对定位元素相邻的话,在某些情况下绝对定位元素将会消失. 产生原因: 只有当绝对定位元素的邻近浮动元素的宽度大于父层宽度减 3 时(即如果父层宽度是 300 ...
- SpringBoot2 JPA No Identifier specified for entity的解决办法
No Identifier specified for entity的错误 此类注解都在 import javax.persistence.*;包下 @Id @GeneratedVal ...
- webpack3--配置多入口和多出口
上一篇我们稍微提到了webpack.config.js.今天主要来说下如何配置多入口,多出口. 我们之前写到的webpack.config.js,具体代码如下: module.exports = { ...
- [hadoop读书笔记] 第四章 Hadoop I/O操作
P92 压缩 P102 序列化 序列化:将结构化对象转为字节流便于在网上传输或写到磁盘进行永久性存储的过程 用于进程之间的通信或者数据的永久存储 反序列化:将字节流转为结构化对象的逆过程 Hadoop ...
- Sword websocket分析二
//websocket发送数据 int send(uint8_t* message, uint64_t message_size) { //掩码 ] = { 0x12, 0x34, 0x56, 0x7 ...
- 关于Unity中的光照(六)
反射探头 1:镜子金属等具有光滑表面的物体都会反射,而游戏中计算实时反射非常消耗CPU的资源, unity5.0新增了一个反射探头的技术,通过采样点,生成反射Cubemap,然后通过特定的着色器从Cu ...
- 3D打印浪潮中的赢家与输家
3D打印浪潮中的赢家与输家 微博 空间 微信 新浪微博 邮箱 QQ好友 人人网 开心网 [导读]虽然目前3D打印行业规模不大且比较分散,但相关上市公司数量惊人.最大的两家是Stratasys和3D S ...
- Eclipse创建一个Maven Web项目
在这篇文章中,我们将演示如何在Eclipse IDE中使用maven创建一个动态Web项目. 使用的工具和技术 - Eclipse Jee Oxygen Maven 3.3.3 JavaSE 1.8 ...