asp.net 图片上传并且截取

很高兴开通了博客园,这里可以记录一些学习的过程,也请大家多多指教。有空就多记录下大家平时都能用到的技术。

功能实现效果:

        

web页面:

View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Posrchev-裁剪头像</title>

    <script src="!js/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="!js/cutpic.js" type="text/javascript"></script>
    <script src="!js/uploadify-v2.1.4/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
    <script src="!js/uploadify-v2.1.4/swfobject.js" type="text/javascript"></script>
    <link href="!css/Main.css" rel="stylesheet" type="text/css" />
    <link href="!css/uploadify.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript"> 
        var imageWidth = 300;
        var imageHeiht = 300;

        $(function () {
            $('#uploadify').uploadify({
                'uploader': '!js/uploadify-v2.1.4/uploadify.swf',
                'script': 'Handler/UploadAvatarHandler.ashx',
                'cancelImg': '!js/uploadify-v2.1.4/cancel.png',
                'folder': 'Temp',
                'queueID': 'fileQueue',
                'auto': true,
                'multi': false,
                'method': 'get',
                'fileExt': '*.jpg;*.png',
                'fileDesc': '请选择jpg , png文件...',
                'scriptData': null,
                'sizeLimit': 2097152,
                'onComplete': function (event, queueID, fileObj, response, data) {
                    if (response.indexOf('Temp') != -1) {

                        $("#bgDiv img").remove();                      //移除截图区里image标签
                        $("#btnSave").show();                          //保存按钮显示                    
                        var result = response.split('$');              //得返回参数

                        var maxVal = 0;
                        if (result[1] > result[2]) {
                            maxVal = result[2];
                        }
                        else {
                            maxVal = result[1];
                        }
                        $("#maxVal").val(maxVal);                     //设置截图区大小

                        $("#hidImageUrl").val(result[0]);             //上传路径存入隐藏域

                        ShowImg(result[0], result[1], result[2]);       //在截图区显示

                        $("#uploadify").uploadifySettings('scriptData', { 'LastImgUrl': $('#hidImageUrl').val() });       //更新参数

                    }
                    else {
                        alert(response);
                    }
                }
            });

            $("#btnSave").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Handler/CutAvatarHandler.ashx",
                    data: { imgUrl: $('#hidImageUrl').val(), pointX: $("#x").val(), pointY: $("#y").val(), maxVal: $("#maxVal").val() },
                    success: function (msg) {
                        if (msg.indexOf('User') != -1) {
                            $("#imgCut").attr("src", msg);
                        }
                        else {
                            alert("error");
                        }
                    },
                    error: function (xhr, msg, e) {
                        alert("error");
                    }
                });
            });
        });
                      
        function ShowImg(imagePath,imgWidth,imgHeight) {           
            var imgPath = imagePath != "" ? imagePath : "!images/ef_pic.jpg";           
            var ic = new ImgCropper("bgDiv", "dragDiv", imgPath, imgWidth, imgHeight, null);
        }                                  
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div class="fl avatarbg">
        <div class="avatarboxbar">
            <div id="bgDiv">
                <div id="dragDiv">
                </div>
            </div>
        </div>
    </div>
    <div class="avatarthumb">
        <asp:Image ID="imgCut" ImageUrl="~/!images/blank_pic.jpg" runat="server" />
    </div>
    <br />
    <div class="uploadimg">
        <div class="upload">
            <div class="uploadswf">
                <input type="file" name="uploadify" id="uploadify" />
            </div>
            <br />
            <p id="fileQueue">
            </p>
        </div>
    </div>
    <input id="btnSave" type="button" value="保存" style="display: none;" />
    <input id="x" runat="server" type="hidden" value="0" />
    <input id="y" runat="server" type="hidden" value="0" />
    <input id="hidImageUrl" type="hidden" value="" />
    <input id="maxVal" runat="server" type="hidden" value="100" />
    </form>
</body>
</html>

一般处理程序页:

    1:上传

View Code
<%@ WebHandler Language="C#" Class="CutAvatarHandler" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
public class CutAvatarHandler : IHttpHandler, IRequiresSessionState
{

    [WebMethod(EnableSession = true)]
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";

        System.IO.Stream stream = null;
        System.Drawing.Image originalImg = null;   //原图
        System.Drawing.Image thumbImg = null;      //缩放图       


        try
        {
            int minWidth = 100;   //最小宽度
            int minHeight = 100;  //最小高度
            int maxWidth = 300;  //最大宽度
            int maxHeight = 300;  //最大高度

            string resultTip = string.Empty;  //返回信息

            HttpPostedFile file = context.Request.Files["Filedata"];      //上传文件      

            string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);  //得到上传路径

            string lastImgUrl = @context.Request.Params["LastImgUrl"];

            if (!string.IsNullOrEmpty(lastImgUrl))
            {
                PubClass.FileDel(HttpContext.Current.Server.MapPath(lastImgUrl));
            }

            if (file != null)
            {
                if (!System.IO.Directory.Exists(uploadPath))
                {
                    System.IO.Directory.CreateDirectory(uploadPath);
                }

                string ext = System.IO.Path.GetExtension(file.FileName).ToLower();   //上传文件的后缀(小写)

                if (ext == ".jpg" || ext == ".png")
                {
                    string flag = "ThumbNail" + DateTime.Now.ToFileTime() + ext;

                    string uploadFilePath = uploadPath + "\\" + flag;   //缩放图文件路径

                    stream = file.InputStream;

                    originalImg = System.Drawing.Image.FromStream(stream);

                    if (originalImg.Width > minWidth && originalImg.Height > minHeight)
                    {
                        thumbImg = PubClass.GetThumbNailImage(originalImg, maxWidth, maxHeight);  //按宽、高缩放

                        if (thumbImg.Width > minWidth && thumbImg.Height > minWidth)
                        {
                            thumbImg.Save(uploadFilePath);

                            resultTip = @context.Request["folder"] + "/" + flag + "$" + thumbImg.Width + "$" + thumbImg.Height;
                        }
                        else
                        {
                            resultTip = "图片比例不符合要求";
                        }
                    }
                    else
                    {
                        resultTip = "图片尺寸必须大于" + minWidth + "*" + minHeight;
                    }
                }
            }
            else
            {
                resultTip = "上传文件为空";
            }

            context.Response.Write(resultTip);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (originalImg != null)
            {
                originalImg.Dispose();
            }

            if (stream != null)
            {
                stream.Close();
                stream.Dispose();
            }

            if (thumbImg != null)
            {
                thumbImg.Dispose();
            }

            GC.Collect();
        }


    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

     2: 截图

View Code
<%@ WebHandler Language="C#" Class="CutAvatarHandler" %>

using System;
using System.Web;
using System.Web.SessionState;

public class CutAvatarHandler : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";

        System.Drawing.Bitmap bitmap = null;   //按截图区域生成Bitmap
        System.Drawing.Image thumbImg = null;      //被截图 
        System.Drawing.Graphics gps = null;    //存绘图对象   
        System.Drawing.Image finalImg = null;  //最终图片
        try
        {
            string pointX = context.Request.Params["pointX"];   //X坐标
            string pointY = context.Request.Params["pointY"];   //Y坐标
            string imgUrl = context.Request.Params["imgUrl"];   //被截图图片地址
            string rlSize = context.Request.Params["maxVal"];        //截图矩形的大小

            int finalWidth = 100;
            int finalHeight = 100;

            if (!string.IsNullOrEmpty(pointX) && !string.IsNullOrEmpty(pointY) && !string.IsNullOrEmpty(imgUrl))
            {

                string ext = System.IO.Path.GetExtension(imgUrl).ToLower();   //上传文件的后缀(小写)

                bitmap = new System.Drawing.Bitmap(Convert.ToInt32(rlSize), Convert.ToInt32(rlSize));

                string jImgUrl = HttpContext.Current.Server.MapPath(imgUrl);
                thumbImg = System.Drawing.Image.FromFile(jImgUrl);

                System.Drawing.Rectangle rl = new System.Drawing.Rectangle(Convert.ToInt32(pointX), Convert.ToInt32(pointY), Convert.ToInt32(rlSize), Convert.ToInt32(rlSize));   //得到截图矩形

                gps = System.Drawing.Graphics.FromImage(bitmap);      //读到绘图对象

                gps.DrawImage(thumbImg, 0, 0, rl, System.Drawing.GraphicsUnit.Pixel);

                finalImg = PubClass.GetThumbNailImage(bitmap, finalWidth, finalHeight);

                string finalPath = "User\\final" + DateTime.Now.ToFileTime() + ext;
                string jpath = HttpContext.Current.Server.MapPath(finalPath);
                jpath = jpath.Replace("Handler\\", "");
                finalImg.Save(jpath);

                bitmap.Dispose();
                thumbImg.Dispose();
                gps.Dispose();
                finalImg.Dispose();
                GC.Collect();

                //如果删除掉就不能进行第二次截取
                //PubClass.FileDel(HttpContext.Current.Server.MapPath(imgUrl));

                context.Response.Write(finalPath);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 

转载于:https://www.cnblogs.com/WendyPark/archive/2013/04/25/3042727.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值