欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-09-03 23:55:47
1、说明   接上一篇文章完成后,又突然用到头像上传并在线裁剪。在网上找个众多例子都没有符合要求的,有一篇文章写的不错,asp.net平台下的图片在线裁剪功能的实现代码(...

1、说明

  接上一篇文章完成后,又突然用到头像上传并在线裁剪。在网上找个众多例子都没有符合要求的,有一篇文章写的不错,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(测试页面)

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

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

<%@ page language="c#" autoeventwireup="true" codebehind="default.aspx.cs" inherits="imgjcrop._default" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>在线裁剪</title>
  <link href="scripts/jcrop/jquery.jcrop.css" rel="stylesheet" type="text/css" />
  <link href="scripts/uploadify-v3.1/uploadify.css" rel="stylesheet" type="text/css" />
  <script src="scripts/jquery.1.9.0.min.js" type="text/javascript"></script>
  <script src="scripts/jcrop/jquery.jcrop.js" type="text/javascript"></script>
  <script src="scripts/uploadify-v3.1/jquery.uploadify-3.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      var jcrop_api, boundx, boundy;
      $("#file_upload").uploadify({
        "auto": true,
        "buttontext": "选择图片",
        "swf": "scripts/uploadify-v3.1/uploadify.swf",
        "uploader": "app_handler/uploadify.ashx?action=upload",
        "filetypeexts": "*.jpg; *.jpeg; *.gif; *.png; *.bmp",
        "filetypedesc": "支持的格式:",
        "multi": false,
        "removecompleted": false,
        "onuploadstart": function (file) {
          $("#file_upload-queue").hide();
        },
        "onuploadsuccess": function (file, data, response) {
          var row = eval("[" + data + "]");
          if (row[0]["status"] == 0) {
            $("#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>");
            $("#cutimg img").each(function () { $(this).attr("src", row[0]["message"]); });
            $("#hidimgurl").val(row[0]["message"]);
            $('#imgoriginal').jcrop({
              onchange: updatepreview,
              onselect: updatepreview,
              aspectratio: 1,
              //maxsize: [120, 120],
              setselect: [0, 0, 120, 120]
            }, function () {
              var bounds = this.getbounds();
              boundx = bounds[0];
              boundy = bounds[1];
              jcrop_api = this;
            });
          } else {
            alert(row[0]["message"]);
          }
        }
      });
 
      function updatepreview(c) {
 
        if (parseint(c.w) > 0) {
          var rx = 120 / c.w;
          var ry = 120 / c.h;
 
          $("#imgpreview").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"
          });
        }
        $("#hidxone").val(c.x);
        $("#hidyone").val(c.y);
        $("#hidxtwo").val(c.hidxtwo);
        $("#hidytwo").val(c.hidytwo);
        $("#hidimgwidth").val(c.w);
        $("#hidimgheight").val(c.h);
      };
    });
 
    function cutsaveimg() {
      $.ajax({
        type: "post",
        url: "app_handler/uploadify.ashx?action=cutsaveimg",
        data: { strimgurl: $("#imgoriginal")[0].src, hidxone: $("#hidxone").val(), hidyone: $("#hidyone").val(), hidimgwidth: $("#hidimgwidth").val(), hidimgheight: $("#hidimgheight").val() },
        datatype: "html",
        success: function (data) {
          var row = eval("[" + data + "]");
          if (row[0]["status"] == 0) { }
          alert(row[0]["message"]);
        }
      });
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="file" id="file_upload" name="file_upload" />
  </div>
  <div id="cutimg">
  </div>
  <asp:hiddenfield id="hidxone" runat="server" />
  <asp:hiddenfield id="hidyone" runat="server" />
  <asp:hiddenfield id="hidxtwo" runat="server" />
  <asp:hiddenfield id="hidytwo" runat="server" />
  <asp:hiddenfield id="hidimgwidth" runat="server" />
  <asp:hiddenfield id="hidimgheight" runat="server" />
  <asp:hiddenfield id="hidimgurl" runat="server" />
  </form>
</body>
</html>

uploadify.ashx(一般处理程序)

<%@ webhandler language="c#" class="uploadifyupload" %>
using system;
using system.collections;
using system.data;
using system.web;
using system.linq;
using system.web.services;
using system.web.services.protocols;
using system.web.sessionstate;
using system.io;
using system.collections.generic;
using system.web.ui.webcontrols;
using system.text;
using system.drawing;
using system.drawing.imaging;
public class uploadifyupload : ihttphandler, irequiressessionstate
{
  public void processrequest(httpcontext context)
  {
    context.response.contenttype = "text/plain";
    context.response.charset = "utf-8";
 
    string action = context.request["action"];
    switch (action)
    {
      case "upload":
        //上传图片
        upload(context);
        break;
      case "cutsaveimg":
        //裁剪并保存
        cutsaveimg(context);
        break;
    }
    context.response.end();
  }
  /// <summary>
  /// 上传图片
  /// </summary>
  /// <param name="context"></param>
  private void upload(httpcontext context)
  {
    httppostedfile postedfile = context.request.files["filedata"];
    if (postedfile != null)
    {
      string filename, fileextension;
      int filesize;
      filename = postedfile.filename;
      filesize = postedfile.contentlength;
      if (filename != "")
      {
        fileextension = postedfile.filename.substring(postedfile.filename.lastindexof('.'));
        string strpath = context.server.mappath("/") + "\\app_file\\upload\\";//设置文件的路径
        string strfilename = "upload" + datetime.now.tostring("yyyymmddhhmmss") + fileextension;
        string strfileurl = strpath + strfilename;//保存文件路径
        if (!directory.exists(strpath))
        {
          directory.createdirectory(strpath);
        }
        postedfile.saveas(strfileurl);//先保存源文件
        context.response.write("{\"status\":0,\"message\":\"/app_file/upload/" + strfilename + "\"}");
      }
      else
      {
        context.response.write("{\"status\":1,\"message\":\"上传失败!\"}");
      }
    }
    else
    {
      context.response.write("{\"status\":1,\"message\":\"上传失败!\"}");
    }
  }
  /// <summary>
  /// 裁剪并保存图片
  /// </summary>
  /// <param name="context"></param>
  private void cutsaveimg(httpcontext context)
  {
    string strimgurl = context.request["strimgurl"];
    string strxone = context.request["hidxone"];
    string stryone = context.request["hidyone"];
    string strimgwidth = context.request["hidimgwidth"];
    string strimgheight = context.request["hidimgheight"];
    string[] urls = strimgurl.split('/');
    string str_url = urls.last();
    try
    {
      string stroldfiel = context.server.mappath("~/app_file/upload/");
      string strnewfiel = context.server.mappath("~/app_file/cut/");
      string stroldurl = path.combine(stroldfiel, str_url);
      string strnewurl = path.combine(strnewfiel, "cut" + datetime.now.tostring("yyyymmddhhmmss") + "." + str_url.split('.')[1]);
      if (!directory.exists(strnewfiel))
      {
        directory.createdirectory(strnewfiel);
      }
      int intstartx = int.parse(strxone);
      int intstarty = int.parse(stryone);
      int intwidth = int.parse(strimgwidth);
      int intheight = int.parse(strimgheight);
      cutgeneratedimage(intstartx, intstarty, intwidth, intheight, stroldurl, strnewurl);
      context.response.write("{\"status\":0,\"message\":\"裁剪成功并保存!\"}");
    }
    catch
    {
      context.response.write("{\"status\":1,\"message\":\"裁剪失败!\"}");
    }
  }
  /// <summary>
  /// 裁剪图片
  /// </summary>
  /// <param name="intwidth">要缩小裁剪图片宽度</param>
  /// <param name="intheight">要缩小裁剪图片长度</param>
  /// <param name="stroldimgurl">要处理图片路径</param>
  /// <param name="strnewimgurl">处理完毕图片路径</param>
  public void cutgeneratedimage(int intstartx, int intstarty, int intwidth, int intheight, string stroldimgurl, string strnewimgurl)
  {
    //上传标准图大小
    int intstandardwidth = 120;
    int intstandardheight = 120;
 
    int intreducewidth = 0; // 缩小的宽度
    int intreduceheight = 0; // 缩小的高度
    int intcutoutwidth = 0; // 裁剪的宽度
    int intcutoutheight = 0; // 裁剪的高度
    int level = 100; //缩略图的质量 1-100的范围
    //获得缩小,裁剪大小
    if (intstandardheight * intwidth / intstandardwidth > intheight)
    {
      intreducewidth = intwidth;
      intreduceheight = intstandardheight * intwidth / intstandardwidth;
      intcutoutwidth = intwidth;
      intcutoutheight = intheight;
    }
    else if (intstandardheight * intwidth / intstandardwidth < intheight)
    {
      intreducewidth = intstandardwidth * intheight / intstandardheight;
      intreduceheight = intheight;
      intcutoutwidth = intwidth;
      intcutoutheight = intheight;
    }
    else
    {
      intreducewidth = intwidth;
      intreduceheight = intheight;
      intcutoutwidth = intwidth;
      intcutoutheight = intheight;
    }
    //通过连接创建image对象
    //system.drawing.image oldimage = system.drawing.image.fromfile(stroldimgurl);
    //oldimage.save(server.mappath("tepm.jpg"));
    //oldimage.dispose();
    //缩小图片
    bitmap bm = new bitmap(stroldimgurl);
    //处理jpg质量的函数
    imagecodecinfo[] codecs = imagecodecinfo.getimageencoders();
    imagecodecinfo ici = null;
    foreach (imagecodecinfo codec in codecs)
    {
      if (codec.mimetype == "image/jpeg")
      {
        ici = codec;
        break;
      }
    }
    encoderparameters ep = new encoderparameters();
    ep.param[0] = new encoderparameter(system.drawing.imaging.encoder.quality, (long)level);
    //裁剪图片
    rectangle clonerect = new rectangle(intstartx, intstarty, intcutoutwidth, intcutoutheight);
    pixelformat format = bm.pixelformat;
    bitmap clonebitmap = bm.clone(clonerect, format);
    //保存图片
    clonebitmap.save(strnewimgurl, ici, ep);
    bm.dispose();
  }
  public bool isreusable
  {
    get
    {
      return false;
    }
  }
}  

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

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

4、最后奉上demo

  imgjcrop

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