http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 18894|回复: 10

[asp.net] asp.net使用Jquery.Jcrop进行图片自由diy剪切上传详解(附源码)

[复制链接]
发表于 2013-8-30 10:46:12 | 显示全部楼层 |阅读模式
            asp.net使用Jquery.Jcrop进行图片自由diy剪切上传教程详解

      前言与基础准备

首先来说这种功能是很常见的,而且也是现代上传图片的一种潮流,自由定制上传就是我们所说的Diy
我们先来准备一下素材吧
1.新建一个asp.net网站如下 ,名称随便起,
2.准备一张504*374的图片
3.下载一个Jquery,和jquery.Jcrop.min.js,jquery.Jcrop.min.css
这些我一会儿打包上传上来大家可以自己下载 的源码进行测试

第一步新建asp.net网站
如下图片
QQ截图20130830100046.jpg
这里面有三个地方需要我们注意
第一个是upload上传图片保存的目录
第二个default.aspx页面
第三个avatarservice.ashx一般处理程序
有了这样。我们先来看看default.aspx页面吧
QQ截图20130830100336.jpg
页面就只有这些,我是拉的控件少的不能再少了,就是想给大家一个原生的,不加任何别的东西。
方便大家使用
一起来看看default.aspx的Html代码
[HTML] 纯文本查看 复制代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Web.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>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.Jcrop.min.js" type="text/javascript"></script>
    <link href="Scripts/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
    <style> .none{ display: none;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <script>
            //上传图片按钮单击事件
            function picclick() {
                if (document.all)
                    document.getElementById("btnupload").click();
                else {
                    var evt = document.createEvent("MouseEvents");
                    evt.initEvent("click", true, true);
                    document.getElementById("btnupload").dispatchEvent(evt);
                }
            }
        </script>
        <%-- 上传控件--%>
        <input type="file" name="photo" runat="server" id="photoFile" />
        <asp:Button ID="btnupload" runat="server" CssClass="none" Text="Button" />
        <p>裁剪前头像(504*374)</p>
        <div class="big" style="width: 504px; height: 374px; overflow: hidden;">
            <img id="photo" runat="server" src="image/0130830091530.jpg" />
        </div>
        <p> 裁剪后头像(120*150)</p>
        <div style="width: 120px; height: 150px; border: 1px solid #dedede; overflow: hidden;">
            <img id="preview" runat="server" src="image/0130830091530.jpg" /></div>
        <%--  x--%>
        <input type="hidden" runat="server" id="px" />
        <%--   y--%>
        <input type="hidden" runat="server" id="py" />
        <%-- width--%>
        <input type="hidden" runat="server" id="pw" />
        <%-- heigh--%>
        <input type="hidden" runat="server" id="ph" />
        <%-- path--%>
        <input type="hidden" runat="server" id="ppath" />
        <input type="button" class="btn" id="btnEnter" value="保存剪切">
        <span style="color: Red;" runat="server" id="tipMsg"></span>
        <script type="text/javascript">
            //保存剪切后的图片
            function save() {
                $.ajax({
                    type: "POST",
                    url: "AvatarService.ashx",
                    data: { myaction: "save", pw: $("#pw").val(),
                        ph: $("#ph").val(), px: $("#px").val(),
                        py: $("#py").val(), ppath: $("#ppath").val()
                    }
                , beforeSend: function () {
                    $("#tipMsg").html("");
                }, success: function (msg) {
                    $("#tipMsg").html(msg);
                    if (msg.indexOf("成功") != -1) {
                        setTimeout('window.location.href = "Default.aspx";', 2000);
                    }
                }, error: function (error) {
                    $("#tipMsg").html(error);
                }
                });
            }
            //            大图片
            $('#photo').Jcrop({
                onChange: showPreview, //选择大图片时执行的事件
                onSelect: setsize, //选择完成后执行的事件
                onRelease: hidePreview,
                aspectRatio: 120 / 150//选择图片的比率
            });
            //            //小图片
            var $preview = $('#preview');
            function showPreview(coords) {
                if (parseInt(coords.w) > 0) {
                    var rx = 120 / coords.w;
                    var ry = 150 / coords.h;
                    previewshow(rx, ry, coords.x, coords.y)
                }
            }
            //显示剪切效果
            function previewshow(rx, ry, x, y) {
                $preview.css({
                    width: Math.round(rx * 500) + 'px',
                    height: Math.round(ry * 370) + 'px',
                    marginLeft: '-' + Math.round(rx * x) + 'px',
                    marginTop: '-' + Math.round(ry * y) + 'px'
                }).show();
            }
            //设置参数
            function hidePreview() {
                $preview.stop().fadeOut('fast');
            }
            //选择后设置各个参数
            function setsize(coords, e) {
                $("#pw").val(coords.w);
                $("#ph").val(coords.h);
                $("#px").val(coords.x);
                $("#py").val(coords.y);
                coords.x = 0;
            }
        </script>
    </div>
    </form>
</body>
</html>

源码里面有注释,我相信不用我多说大家就能看明白
然后再来CS下的代码
[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace Web
{
    public partial class Default : System.Web.UI.Page
    {
        string img = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            preview.Src = img;
        }

        protected void btnupload_Click(object sender, EventArgs e)
        {
            string msg = "";
            string ww = "0";
            HttpPostedFile file = photoFile.PostedFile;
            if (!file.ContentType.Contains("image"))
            {
                msg = "照片格式不合法";
                return;
            }
            string ext = Path.GetExtension(file.FileName).ToLower();
            if (ext != ".jpg" && ext != ".gif" && ext != ".png" && ext != ".jpeg")
            {
                msg = "请您上传jpg、gif、png图片";
            }
            if (file.ContentLength > 5 * 1024 * 1024)
            {
                msg = "请您上传512字节内的图片";
            }
            string newName = Guid.NewGuid().ToString();
            string tempPath = "image/upload/";

            img = tempPath + newName + ext;
            string filePath = Server.MapPath(img);
            tempPath = Server.MapPath(tempPath);
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            using (System.Drawing.Image originalImage = System.Drawing.Image.FromStream(file.InputStream))
            {
                float sw = 0;
                System.Drawing.Image.GetThumbnailImageAbort callback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                originalImage.GetThumbnailImage(497, 367, callback, IntPtr.Zero).Save(filePath);
                ww = sw.ToString();
                msg = img;
            }
            tipMsg.InnerText = "上传成功";
            photo.Src = msg;
            preview.Src = msg;
            ppath.Value = msg;
        }

        public bool ThumbnailCallback()
        {
            return false;
        }
    }
}

很简单吧

再来看看AvatarService 的代码
[C#] 纯文本查看 复制代码
<%@ WebHandler Language="C#" Class="AvatarService" %>
using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public class AvatarService : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string action = context.Request["myaction"];
        if (action == "save")
        {
            float pw = float.Parse(context.Request["pw"]);
            float ph = float.Parse(context.Request["ph"]);
            float px = float.Parse(context.Request["px"]);
            float py = float.Parse(context.Request["py"]);

            string ppath = context.Request["ppath"];
            ppath = context.Server.MapPath(ppath);
            string imgpath = string.Empty;
            Bitmap b = new Bitmap(ppath);

            string extend = Path.GetExtension(ppath).ToLower();
            //剪裁图片
            RectangleF rec = new RectangleF(px, py, pw, ph);
            Bitmap nb = b.Clone(rec, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            //从重保存图片
            ppath = ppath.Replace(extend, "") + "_sml" + extend;
            nb.Save(ppath);
            context.Response.Write("保存成功!");

        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

好了我们一起来看看效果吧
运行
QQ截图20130830100805.jpg
我们现在选择一张图片进行上传
QQ截图20130830101019.jpg
为了和默认图片区分开,我们来选择一张别的图片
然后单击打开
QQ截图20130830101034.jpg
看效果图片传来了
而且会自动剪切
我们现在可能自由选择了
只要将鼠标放到大图上就可以有效果出现,如下图
QQ截图20130830101114.jpg
在保存之前我们一起来看看图片目录下吧
QQ截图20130830101200.jpg
我们能清楚的看到只有我们刚才选择的大图片
下面我们单击一下保存按钮
QQ截图20130830101222.jpg
是不是多出来一张,我们刚选择的图片的一部分哦,
放大看看
QQ截图20130830101229.jpg
对就是我刚选择的部分,截图并上传成功了。
下面我提供下源码大家要吧亲自进行测试

Web.zip (587.37 KB, 下载次数: 697)

本帖被以下淘专辑推荐:



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
发表于 2013-8-30 10:54:16 | 显示全部楼层
这个比较有用,喜欢
发表于 2013-8-30 11:03:53 | 显示全部楼层
呦嘻  马上就要用到这个功能 飞哥吊你一下
发表于 2013-8-30 11:32:23 | 显示全部楼层
哈哈,这个功能不错。。
发表于 2013-8-30 11:33:57 | 显示全部楼层
这功能酷炫碉炸天,顶飞老大
发表于 2013-8-30 11:42:33 | 显示全部楼层
看贴留名
回复

使用道具 举报

发表于 2013-9-6 08:29:43 | 显示全部楼层
谢谢楼主,好久没看到这么好的贴了
发表于 2013-9-24 15:23:17 | 显示全部楼层
回复

使用道具 举报

发表于 2014-2-17 13:58:04 | 显示全部楼层
谢谢站长  ,再一次受教了
发表于 2014-4-30 17:29:11 | 显示全部楼层
受教了,学习中……
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-26 04:56

© 2014-2021

快速回复 返回顶部 返回列表