当前位置:Gxlcms > asp.net > 基于asp.net实现图片在线上传并在线裁剪功能

基于asp.net实现图片在线上传并在线裁剪功能

时间:2021-07-01 10:21:17 帮助过:6人阅读

1、说明

  接上一篇文章asp.net uploadify实现多附件上传功能完成后,又突然用到头像上传并在线裁剪。在网上找个众多例子都没有符合要求的,有一篇文章写的不错,Asp.Net平台下的图片在线裁剪功能的实现代码(源码打包),大家可以看下

2、组成

  首先说明一下代码实现所用到的技术,仅供参考:

    开发工具:vs2010

    目标框架:.NET Framework3.5

    jcrop:Jcrop.js v0.9.12

    Uploadify:uploadify-v3.1

    Jquery:jquery-1.9.0.js

  最后我会将整个Demo上传,如果同学们的电脑上有开发环境可直接打开项目解决方案运行。

3、代码

Default.aspx(测试页面)

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImgJcrop._Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>在线裁剪</title>
  6. <link href="Scripts/jcrop/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
  7. <link href="Scripts/uploadify-v3.1/uploadify.css" rel="stylesheet" type="text/css" />
  8. <script src="Scripts/jquery.1.9.0.min.js" type="text/javascript"></script>
  9. <script src="Scripts/jcrop/jquery.Jcrop.js" type="text/javascript"></script>
  10. <script src="Scripts/uploadify-v3.1/jquery.uploadify-3.1.js" type="text/javascript"></script>
  11. <script type="text/javascript">
  12. $(function () {
  13. var jcrop_api, boundx, boundy;
  14. $("#file_upload").uploadify({
  15. "auto": true,
  16. "buttonText": "选择图片",
  17. "swf": "Scripts/uploadify-v3.1/uploadify.swf",
  18. "uploader": "App_Handler/Uploadify.ashx?action=upload",
  19. "fileTypeExts": "*.jpg; *.jpeg; *.gif; *.png; *.bmp",
  20. "fileTypeDesc": "支持的格式:",
  21. "multi": false,
  22. "removeCompleted": false,
  23. "onUploadStart": function (file) {
  24. $("#file_upload-queue").hide();
  25. },
  26. "onUploadSuccess": function (file, data, response) {
  27. var row = eval("[" + data + "]");
  28. if (row[0]["status"] == 0) {
  29. $("#cutimg").html("<img id=\"imgOriginal\" name=\"imgOriginal\" /><div style=\"overflow: hidden; margin-top: 20px;\"><div style=\"width: 120px; height: 120px; overflow: hidden;\"><img id=\"imgPreview\" /></div><br /><input type=\"button\" id=\"btnImgCut\" onclick=\"cutSaveImg()\" value=\"裁剪并保存图片\" /></div>");
  30. $("#cutimg img").each(function () { $(this).attr("src", row[0]["message"]); });
  31. $("#hidImgUrl").val(row[0]["message"]);
  32. $('#imgOriginal').Jcrop({
  33. onChange: updatePreview,
  34. onSelect: updatePreview,
  35. aspectRatio: 1,
  36. //maxSize: [120, 120],
  37. setSelect: [0, 0, 120, 120]
  38. }, function () {
  39. var bounds = this.getBounds();
  40. boundx = bounds[0];
  41. boundy = bounds[1];
  42. jcrop_api = this;
  43. });
  44. } else {
  45. alert(row[0]["message"]);
  46. }
  47. }
  48. });
  49. function updatePreview(c) {
  50. if (parseInt(c.w) > 0) {
  51. var rx = 120 / c.w;
  52. var ry = 120 / c.h;
  53. $("#imgPreview").css({
  54. width: Math.round(rx * boundx) + "px",
  55. height: Math.round(ry * boundy) + "px",
  56. marginLeft: "-" + Math.round(rx * c.x) + "px",
  57. marginTop: "-" + Math.round(ry * c.y) + "px"
  58. });
  59. }
  60. $("#hidXone").val(c.x);
  61. $("#hidYone").val(c.y);
  62. $("#hidXtwo").val(c.hidXtwo);
  63. $("#hidYtwo").val(c.hidYtwo);
  64. $("#hidImgWidth").val(c.w);
  65. $("#hidImgHeight").val(c.h);
  66. };
  67. });
  68. function cutSaveImg() {
  69. $.ajax({
  70. type: "post",
  71. url: "App_Handler/Uploadify.ashx?action=cutsaveimg",
  72. data: { strImgUrl: $("#imgOriginal")[0].src, hidXone: $("#hidXone").val(), hidYone: $("#hidYone").val(), hidImgWidth: $("#hidImgWidth").val(), hidImgHeight: $("#hidImgHeight").val() },
  73. dataType: "html",
  74. success: function (data) {
  75. var row = eval("[" + data + "]");
  76. if (row[0]["status"] == 0) { }
  77. alert(row[0]["message"]);
  78. }
  79. });
  80. }
  81. </script>
  82. </head>
  83. <body>
  84. <form id="form1" runat="server">
  85. <div>
  86. <input type="file" id="file_upload" name="file_upload" />
  87. </div>
  88. <div id="cutimg">
  89. </div>
  90. <asp:HiddenField ID="hidXone" runat="server" />
  91. <asp:HiddenField ID="hidYone" runat="server" />
  92. <asp:HiddenField ID="hidXtwo" runat="server" />
  93. <asp:HiddenField ID="hidYtwo" runat="server" />
  94. <asp:HiddenField ID="hidImgWidth" runat="server" />
  95. <asp:HiddenField ID="hidImgHeight" runat="server" />
  96. <asp:HiddenField ID="hidImgUrl" runat="server" />
  97. </form>
  98. </body>
  99. </html>

Uploadify.ashx(一般处理程序)

  1. <%@ WebHandler Language="C#" Class="UploadifyUpload" %>
  2. using System;
  3. using System.Collections;
  4. using System.Data;
  5. using System.Web;
  6. using System.Linq;
  7. using System.Web.Services;
  8. using System.Web.Services.Protocols;
  9. using System.Web.SessionState;
  10. using System.IO;
  11. using System.Collections.Generic;
  12. using System.Web.UI.WebControls;
  13. using System.Text;
  14. using System.Drawing;
  15. using System.Drawing.Imaging;
  16. public class UploadifyUpload : IHttpHandler, IRequiresSessionState
  17. {
  18. public void ProcessRequest(HttpContext context)
  19. {
  20. context.Response.ContentType = "text/plain";
  21. context.Response.Charset = "utf-8";
  22. string action = context.Request["action"];
  23. switch (action)
  24. {
  25. case "upload":
  26. //上传图片
  27. upload(context);
  28. break;
  29. case "cutsaveimg":
  30. //裁剪并保存
  31. cutsaveimg(context);
  32. break;
  33. }
  34. context.Response.End();
  35. }
  36. /// <summary>
  37. /// 上传图片
  38. /// </summary>
  39. /// <param name="context"></param>
  40. private void upload(HttpContext context)
  41. {
  42. HttpPostedFile postedFile = context.Request.Files["Filedata"];
  43. if (postedFile != null)
  44. {
  45. string fileName, fileExtension;
  46. int fileSize;
  47. fileName = postedFile.FileName;
  48. fileSize = postedFile.ContentLength;
  49. if (fileName != "")
  50. {
  51. fileExtension = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
  52. string strPath = context.Server.MapPath("/") + "\\App_File\\Upload\\";//设置文件的路径
  53. string strFileName = "upload" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;
  54. string strFileUrl = strPath + strFileName;//保存文件路径
  55. if (!Directory.Exists(strPath))
  56. {
  57. Directory.CreateDirectory(strPath);
  58. }
  59. postedFile.SaveAs(strFileUrl);//先保存源文件
  60. context.Response.Write("{\"status\":0,\"message\":\"/App_File/Upload/" + strFileName + "\"}");
  61. }
  62. else
  63. {
  64. context.Response.Write("{\"status\":1,\"message\":\"上传失败!\"}");
  65. }
  66. }
  67. else
  68. {
  69. context.Response.Write("{\"status\":1,\"message\":\"上传失败!\"}");
  70. }
  71. }
  72. /// <summary>
  73. /// 裁剪并保存图片
  74. /// </summary>
  75. /// <param name="context"></param>
  76. private void cutsaveimg(HttpContext context)
  77. {
  78. string strImgUrl = context.Request["strImgUrl"];
  79. string strXone = context.Request["hidXone"];
  80. string strYone = context.Request["hidYone"];
  81. string strImgWidth = context.Request["hidImgWidth"];
  82. string strImgHeight = context.Request["hidImgHeight"];
  83. string[] urls = strImgUrl.Split('/');
  84. string str_url = urls.Last();
  85. try
  86. {
  87. string strOldFiel = context.Server.MapPath("~/App_File/Upload/");
  88. string strNewFiel = context.Server.MapPath("~/App_File/Cut/");
  89. string strOldUrl = Path.Combine(strOldFiel, str_url);
  90. string strNewUrl = Path.Combine(strNewFiel, "cut" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + str_url.Split('.')[1]);
  91. if (!Directory.Exists(strNewFiel))
  92. {
  93. Directory.CreateDirectory(strNewFiel);
  94. }
  95. int intStartX = int.Parse(strXone);
  96. int intStartY = int.Parse(strYone);
  97. int intWidth = int.Parse(strImgWidth);
  98. int intHeight = int.Parse(strImgHeight);
  99. CutGeneratedImage(intStartX, intStartY, intWidth, intHeight, strOldUrl, strNewUrl);
  100. context.Response.Write("{\"status\":0,\"message\":\"裁剪成功并保存!\"}");
  101. }
  102. catch
  103. {
  104. context.Response.Write("{\"status\":1,\"message\":\"裁剪失败!\"}");
  105. }
  106. }
  107. /// <summary>
  108. /// 裁剪图片
  109. /// </summary>
  110. /// <param name="intWidth">要缩小裁剪图片宽度</param>
  111. /// <param name="intHeight">要缩小裁剪图片长度</param>
  112. /// <param name="strOldImgUrl">要处理图片路径</param>
  113. /// <param name="strNewImgUrl">处理完毕图片路径</param>
  114. public void CutGeneratedImage(int intStartX, int intStartY, int intWidth, int intHeight, string strOldImgUrl, string strNewImgUrl)
  115. {
  116. //上传标准图大小
  117. int intStandardWidth = 120;
  118. int intStandardHeight = 120;
  119. int intReduceWidth = 0; // 缩小的宽度
  120. int intReduceHeight = 0; // 缩小的高度
  121. int intCutOutWidth = 0; // 裁剪的宽度
  122. int intCutOutHeight = 0; // 裁剪的高度
  123. int level = 100; //缩略图的质量 1-100的范围
  124. //获得缩小,裁剪大小
  125. if (intStandardHeight * intWidth / intStandardWidth > intHeight)
  126. {
  127. intReduceWidth = intWidth;
  128. intReduceHeight = intStandardHeight * intWidth / intStandardWidth;
  129. intCutOutWidth = intWidth;
  130. intCutOutHeight = intHeight;
  131. }
  132. else if (intStandardHeight * intWidth / intStandardWidth < intHeight)
  133. {
  134. intReduceWidth = intStandardWidth * intHeight / intStandardHeight;
  135. intReduceHeight = intHeight;
  136. intCutOutWidth = intWidth;
  137. intCutOutHeight = intHeight;
  138. }
  139. else
  140. {
  141. intReduceWidth = intWidth;
  142. intReduceHeight = intHeight;
  143. intCutOutWidth = intWidth;
  144. intCutOutHeight = intHeight;
  145. }
  146. //通过连接创建Image对象
  147. //System.Drawing.Image oldimage = System.Drawing.Image.FromFile(strOldImgUrl);
  148. //oldimage.Save(Server.MapPath("tepm.jpg"));
  149. //oldimage.Dispose();
  150. //缩小图片
  151. Bitmap bm = new Bitmap(strOldImgUrl);
  152. //处理JPG质量的函数
  153. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  154. ImageCodecInfo ici = null;
  155. foreach (ImageCodecInfo codec in codecs)
  156. {
  157. if (codec.MimeType == "image/jpeg")
  158. {
  159. ici = codec;
  160. break;
  161. }
  162. }
  163. EncoderParameters ep = new EncoderParameters();
  164. ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);
  165. //裁剪图片
  166. Rectangle cloneRect = new Rectangle(intStartX, intStartY, intCutOutWidth, intCutOutHeight);
  167. PixelFormat format = bm.PixelFormat;
  168. Bitmap cloneBitmap = bm.Clone(cloneRect, format);
  169. //保存图片
  170. cloneBitmap.Save(strNewImgUrl, ici, ep);
  171. bm.Dispose();
  172. }
  173. public bool IsReusable
  174. {
  175. get
  176. {
  177. return false;
  178. }
  179. }
  180. }  

4、最后奉上Demo

  ImgJcrop

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,同时也希望多多支持脚本之家!

人气教程排行