标题:Asp.Net+flash+jquery.TY.js涂鸦插件,可保存涂鸦图片
作者:网友
日期:2023-06-15 18:10:20
内容:

  20132-20更新:增加了加载图片的缩放功能。将缩放后的宽度传到动态页,动态页获取后重新计算坐标位置后绘图。如果涂鸦不和图片合成,当宽度小于默认的650,绘制一条分隔线。

  Asp.Net+flash+jquery实现的在线涂鸦插件,通过将涂鸦数据发送到ashx页面,ashx获取到数据后绘制图片并保存涂鸦图片。

  本示例基于謾軻(Manction),http://manction.51.com简易涂鸦板修改,增加了重做,画笔颜色,大小和透明度,保存功能。

  flash可以加载指定的站内图片进行涂鸦,保存后绘制的数据和原始图片合并生成新涂鸦图片

  示例

  效果如下

Asp.Net+flash+jquery.TY.js涂鸦插件,可保存涂鸦图片

test.html

<!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><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.7.1/jquery.min.js"></script><title>Asp.Net+flash+jquery.TY.js涂鸦插件,可保存涂鸦图片</title><meta content="在线涂鸦,保存涂鸦图片,asp.net保存涂鸦,flash涂鸦" name="Keywords"/><meta content="Asp.Net+flash+jquery实现的在线涂鸦插件,通过将涂鸦数据发送到ashx页面,通过asp.net绘制图片。" name="description"/><script type="text/javascript">window.onload=function(){    (function ($) {        //cfg配置说明,JSON对象        //swf:涂鸦swf文件路径,默认值为:ty.swf        //height:高度,默认值为400,高度小于400会隐藏flash起来,最终生成的涂鸦图片高度基于这个值。如果指定img将会忽略此配置,依据原始图片尺寸        //width:宽度,默认值:650。注意:这里的宽度是最终生成的图片宽度,不会改变UI的宽度,因为小于650会导致菜单显示不全。最终生成的涂鸦图片高度基于这个值。如果指定img将会忽略此配置,依据原始图片尺寸        //img:flash要加载的图片,绘制的涂鸦信息和此图片合成,默认不加载图片。只能加载站内图片,站外图片动态页没有添加图片下载功能        //url:绘图的涂鸦数据提交到的页面,如果要保存图片一定要传递此配置,否则无法保存图片,不保存图片时url,success和error回调可以不传递        //success:保存涂鸦时成功的回调函数,回调中的this为容器div对象,参数为返回的json对象        //error:保存涂鸦失败时回调函数,回调中this为容器div对象,参数为返回的json对象        //data:ajax提交时附加的参数,JSON对象,如数据库中对应ID什么的        //debug:如果为true,则输出xhr返回的responseText信息        //ext:保存图片扩展名,默认为jpg,不带.        //wstep:如果传递了img,每次缩放图片宽度的大小,默认20。高度依据图片原始尺寸等比算出        $.fn.TY = function (cfg) {            var cbPrefix = 'doPost', cbMark = 'mark', tm, ie = !!document.all;            function FlashVars(config) {                var s = '';                if (config.cbName) s += '&cb=' + config.cbName;                if (config.markName) s += '&mk=' + config.markName;                if (config.img) s += '&img=' + config.img;                else if (config.width < 650) s += '&spl=' + config.width; //宽度小于UI宽度则传递此参数给flash绘制分隔线                if (config.wstep) s += '&wstep=' + config.wstep;                return s == '' ? '' : s.substring(1);            }            return this.each(function () {                var me = $(this), config = $.extend({ swf: 'ty.swf', height: 400, width: 650, ext: 'jpg', wstep: 20 }, cfg);                tm = new Date().getTime();                if (config.url) { //需要保存涂鸦图片则注册flash调用的javascript方法                    config.cbName = cbPrefix + tm;                    //drawdata,字符串,结构:[{data:[[x,y],[x,y]...],lw:线条宽,color:线条颜色,alpha:线条透明度}.....]                    //newwidth:缩放后图片宽度,发送到服务器用于计算缩放比率,矫正坐标用的,不是图片忽略次参数                    window[config.cbName] = function (drawdata, newwidth) {                        if (!drawdata) alert('没有绘制涂鸦信息!');                        else {                            window[config.markName]('正在保存图片...');                            var data = cfg.data ? cfg.data : {};                            data.w = config.width; data.h = config.height; data.ext = config.ext; data.newwidth = newwidth;                            if (config.img) data.img = config.img; //这个也可以不传,可以通过读取数据库获取到原始图片地址什么的,但是data对象要配置有记录的ID                            data.drawdata = drawdata;                            $.ajax({ url: config.url, type: 'POST', data: data, complete: function (xhr) {                                window[config.markName]('none');                                var r;                                if (200 == xhr.status) try { r = eval('(' + xhr.responseText + ')'); } catch (ex) { r = { success: false, err: '返回的JSON格式不正确!' + (config.debug ? '/n/n' + xhr.responseText : '') }; }                                else r = { success: false, err: 404 == xhr.status ? '动态页路径不对!' : '动态页发生错误!' + (config.debug ? '/n/n' + xhr.responseText : '') };                                if (r.success) {                                    if (config.success) config.success.call(me.get(0), r);                                }                                else if (config.error) config.error.call(me.get(0), r);                            }                            });                        }                    }                }                if (config.img || cfg.url) {                    config.markName = cbMark + tm;                    window[config.markName] = function (display) {                        if (display == 'none') me.find('div').hide();                        else { me.find('div:last').html(display); me.find('div').show(); }                    }                }                me.css({ width: 650, height: config.height, overflow: 'hidden', position: 'relative', border: 'solid 1px #000000' }).append(                ie ? '<object id="swf' + tm + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="650px" height="400px">'                + '<param name="src" value="' + config.swf + '"><param name="FlashVars" value="' + FlashVars(config) + '"><param name="wmode" value="transparent"></object>'                : '<embed width="650px" height="400px" id="swf' + tm + '" type="application/x-shockwave-flash" src="' + config.swf + '?' + FlashVars(config) + '" wmode="transparent"/>');                if (config.img || cfg.url) {                    me.append('<div style="background:#000000;' + (config.img ? '' : 'display:none;') + 'filter:alpha(opacity:50);opacity:.5;width:100%;height:100%;position:absolute;left:0px;height:100%;top:0px;"></div>');                    me.append('<div style="position:absolute;left:43%;top:45%;color:#ffffff;' + (config.img ? '' : 'display:none;') + '">正在加载加载...</div>');                }            });        };    })(jQuery);        $('#dvTY').TY({            height: 300,            width:200,            img: '/imgdesign/ty/123.jpg',            url: '/imgdesign/ty/save.ashx',            swf: '/imgdesign/ty/ty.swf',            data: { id: 123 }, //附加数据            debug: true,            success: function (d) {                alert('涂鸦保存成功!');                $('#dvRst').html('<a href="/imgdesign/ty/' + d.fn + '" target="_blank">点击查看图片</a>');            },            error: function (d) {                alert(d.err);            }        });    }</script></head><body><div id="dvTY"></div><div id="dvRst"></div></body></html>

save.ashx

<%@ WebHandler Language="C#" Class="save" %>using System;using System.Web;using System.Drawing;using Newtonsoft.Json;using System.Collections.Generic;using System.IO;using System.Text.RegularExpressions;public class save : IHttpHandler {    //drawdata结构:[{data:[[x,y],[x,y]...],lw:线条宽,color:线条颜色,alpha:线条透明度}.....]    //每条线的信息    public class DrawData    {        private List<float[]> _data;        private int _lw;        private int _alpha;        private string _color;        /// <summary>        /// 线条信息        /// </summary>        public List<float[]> data { get { return _data; } set { _data = value; } }        /// <summary>        /// 画笔宽        /// </summary>        public int lw { get { return _lw; } set { _lw = value; } }        /// <summary>        /// 画笔透明度,C#下是0~255,需要转换一下        /// </summary>        public int alpha { get { return (int)Math.Floor(_alpha * 2.55); } set { _alpha = value; } }        /// <summary>        /// 画笔颜色        /// </summary>        public string color { get { return _color; } set { _color = value; } }    }    /// <summary>    /// 线条数组转换为顶点数组    /// </summary>    /// <param name="data">线条数据</param>    /// <param name="IsImg">绘制在图片上,不在25~h+25范围内的数据去掉</param>    /// <param name="h">图片高</param>    /// <param name="w">图片宽</param>    /// <param name="newwidth">flash中缩放后的宽,不是绘制在图片上忽略</param>    /// <returns></returns>    protected PointF[] GetPointFs(List<float[]> data, bool IsImg, float h, float w, float newwidth)    {        float top = IsImg ? 25 : 0, scale = IsImg ? w / newwidth : 1;//坐标点缩放比率,不是图片忽略此设置        List<PointF> points = new List<PointF>();        foreach (float[] d in data)        {            points.Add(new PointF(d[0] * scale, (d[1] - top) * scale));        }        return points.ToArray();    }    public void ProcessRequest(HttpContext context)    {        string img = context.Request.Form["img"], w = context.Request.Form["w"], h = context.Request.Form["h"]            , drawdata = context.Request.Form["drawdata"], newwidth = context.Request.Form["newwidth"]            , fn = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + context.Request.Form["ext"];//新文件名        Regex rxInt = new Regex(@"^/d+$", RegexOptions.Compiled);        List<DrawData> data = (List<DrawData>)JsonConvert.DeserializeObject(drawdata, typeof(List<DrawData>));        Bitmap bm;        bool IsImg = false;        float fW = 0, fH = 0, fNewWidth = 0;        if (!string.IsNullOrEmpty(img) && File.Exists(context.Server.MapPath(img)))        {//存在图片            bm = new Bitmap(context.Server.MapPath(img));            IsImg = true;            fW = bm.Width;            fH = bm.Height;            if (!string.IsNullOrEmpty(newwidth) && rxInt.IsMatch(newwidth)) fNewWidth = float.Parse(newwidth);            else fNewWidth = fW;        }        else        {            fW = !string.IsNullOrEmpty(w) && rxInt.IsMatch(w) ? float.Parse(w) : 650;            fH = !string.IsNullOrEmpty(h) && rxInt.IsMatch(h) ? float.Parse(h) : 400;            bm = new Bitmap((int)fW, (int)fH);        }        Color color = Color.White;        using (Graphics g = Graphics.FromImage(bm))        {            foreach (DrawData d in data)            {                color = Color.FromArgb(d.alpha, ColorTranslator.FromHtml("#" + d.color));                using (Pen pen = new Pen(color, d.lw))                {                    g.DrawLines(pen, GetPointFs(d.data, IsImg, fH, fW, fNewWidth));                }            }        }        bm.Save(context.Server.MapPath(fn));        bm.Dispose();        context.Response.Write("{success:true,fn:'" + fn + "',xsc:'" + ((float)fW / (float)fNewWidth).ToString() + "|" + newwidth + "'}");    }     public bool IsReusable {        get {            return false;        }    }}


返回列表 网站首页