基于asp.net如何实现图片在线上传并在线裁剪功能
创始人
2024-11-28 06:03:53
0次

组成

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

    开发工具:vs2010

    目标框架:.NET Framework3.5

    jcrop:Jcrop.js v0.9.12

    Uploadify:uploadify-v3.1

    Jquery:jquery-1.9.0.js

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

代码

Default.aspx(测试页面)

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

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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImgJcrop._Default" %>



  在线裁剪
  
  
  
  
  
  
    $(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("
");             $("#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"]);         }       });     }         
       
     
                       

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();
  }
  /// 
  /// 上传图片
  /// 
  /// 
  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\":\"上传失败!\"}");
    }
  }
  /// 
  /// 裁剪并保存图片
  /// 
  /// 
  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\":\"裁剪失败!\"}");
    }
  }
  /// 
  /// 裁剪图片
  /// 
  /// 要缩小裁剪图片宽度
  /// 要缩小裁剪图片长度
  /// 要处理图片路径
  /// 处理完毕图片路径
  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如何实现图片在线上传并在线裁剪功能

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...