更新:增加图片的缩放,绘制分隔线。字数限制,没更新这里的代码
好久没写什么东东了,将年前一个同学遇到的问题改了下,做了个简易的涂鸦板
Asp.Net+flash+jquery实现的在线涂鸦插件,通过将涂鸦数据发送到ashx页面,ashx获取到数据后绘制图片并保存涂鸦图片。
本示例基于謾軻(Manction),http://manction.51.com简易涂鸦板修改,增加了重做,画笔颜色,大小和透明度,保存功能。
flash可以加载指定的站内图片进行涂鸦,保存后绘制的数据和原始图片合并生成新涂鸦图片
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/>
<scripttype="text/javascript"src="/js/jquery.js"></script>
<title>Asp.Net+flash+jquery.TY.js涂鸦插件,可保存涂鸦图片</title>
<metacontent="在线涂鸦,保存涂鸦图片,asp.net保存涂鸦,flash涂鸦"name="Keywords"/>
<metacontent="Asp.Net+flash+jquery实现的在线涂鸦插件,通过将涂鸦数据发送到ashx页面,通过asp.net绘制图片。"name="description"/>
<scripttype="text/javascript">
(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,不带.
$.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;
return s == '' ? '' : s.substring(1);
}
return this.each(function () {
var me = $(this), config = $.extend({ swf: 'ty.swf', height: 400, width: 650, ext: 'jpg' }, cfg);
tm = new Date().getTime();
if (config.url) { //需要保存涂鸦图片则注册flash调用的javascript方法
config.cbName = cbPrefix + tm;
window[config.cbName] = function (drawdata) {//drawdata,字符串,结构:[{data:[[x,y],[x,y]...],lw:线条宽,color:线条颜色,alpha:线条透明度}.....]
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;
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 ? '<objectid="swf' + tm + '"classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"width="650px"height="400px">'
+ '<paramname="src"value="' + config.swf + '"><paramname="FlashVars"value="' + FlashVars(config) + '"><paramname="wmode"value="transparent"></object>'
: '<embedwidth="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('<divstyle="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('<divstyle="position:absolute;left:43%;top:45%;color:#ffffff;' + (config.img ? '' : 'display:none;') + '">正在加载加载...</div>');
}
});
};
})(jQuery);
window.onload=function () {
$('#dvTY').TY({
height: 300,
img: '/imgdesign/ty/123.jpg',
swf: '/imgdesign/ty/ty.swf',
url: '/imgdesign/ty/save.ashx',
data: { id: 123 }, //附加数据
debug: true,
success: function (d) {
alert('涂鸦保存成功!');
$('#dvRst').html('<ahref="/imgdesign/ty/' + d.fn + '"target="_blank">点击查看图片</a>');
},
error: function (d) {
alert(d.err);
}
});
};
</script>
</head>
<body>
<divid="dvTY"></div>
<divid="dvRst"></div>
</body>
</html>
<%@ WebHandler Language="C#"Class="save"%>
usingSystem;
usingSystem.Web;
usingSystem.Drawing;
usingNewtonsoft.Json;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Text.RegularExpressions;
publicclasssave : IHttpHandler {
//drawdata结构:[{data:[[x,y],[x,y]...],lw:线条宽,color:线条��色,alpha:线条透明度}.....]
//每条线的信息
publicclassDrawData
{
privateList<int[]> _data;
privateint_lw;
privatebyte_alpha;
privatestring_color;
/// <summary>
/// 线条信息
/// </summary>
publicList<int[]> data { get{ return_data; } set{ _data = value; } }
/// <summary>
/// 画笔宽
/// </summary>
publicintlw { get{ return_lw; } set{ _lw = value; } }
/// <summary>
/// 画笔透明度,C#下是0~255,需要转换一下
/// </summary>
publicbytealpha { get{ return(byte)Math.Floor(_alpha * 2.55); } set{ _alpha = value; } }
/// <summary>
/// 画笔颜色
/// </summary>
publicstringcolor { 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>
/// <returns></returns>
protectedPoint[] GetPoints(List<int[]> data, boolIsImg, inth, intw)
{
inttop = IsImg?25:0, bottom = top + h;
List<Point> points = newList<Point>();
foreach(int[] d indata)
{
if((IsImg && d[0] < w && d[1] >= top && d[1] <= bottom) || (!IsImg && d[0] < w && d[1] < h))
points.Add(newPoint(d[0], d[1]-top));//注意y要减去top当配置了img时,应为img加载位置离顶部25px的位置
}
returnpoints.ToArray();
}
publicvoidProcessRequest(HttpContext context)
{
stringimg = context.Request.Form["img"], w = context.Request.Form["w"], h = context.Request.Form["h"]
, drawdata = context.Request.Form["drawdata"]
, fn = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "."+ context.Request.Form["ext"];//新文件名
Regex rxInt = newRegex(@"^\d+$", RegexOptions.Compiled);
List<DrawData> data = (List<DrawData>)JsonConvert.DeserializeObject(drawdata, typeof(List<DrawData>));
Bitmap bm;
boolIsImg=false;
intintW, intH;
if(!string.IsNullOrEmpty(img) && File.Exists(context.Server.MapPath(img))){//存在图片
bm = newBitmap(context.Server.MapPath(img));
IsImg=true;
intW = bm.Width;
intH = bm.Height;
}
else
{
intW = rxInt.IsMatch(w) ? int.Parse(w) : 650;
intH = rxInt.IsMatch(h) ? int.Parse(h) : 400;
bm = newBitmap(intW, intH);
}
Color color = Color.White;
using(Graphics g = Graphics.FromImage(bm))
{
foreach(DrawData d indata)
{
color = Color.FromArgb(d.alpha, ColorTranslator.FromHtml("#"+ d.color));
using(Pen pen = newPen(color, d.lw))
{
g.DrawLines(pen, GetPoints(d.data, IsImg, intH, intW));
}
}
}
bm.Save(context.Server.MapPath(fn));
bm.Dispose();
context.Response.Write("{success:true,fn:'"+ fn + "'}");
}
publicboolIsReusable {
get{
returnfalse;
}
}
}
<%@ WebHandler Language="C#"Class="save"%>
usingSystem;
usingSystem.Web;
usingSystem.Drawing;
usingNewtonsoft.Json;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Text.RegularExpressions;
publicclasssave : IHttpHandler {
//drawdata结构:[{data:[[x,y],[x,y]...],lw:线条宽,color:线条颜色,alpha:线条透明度}.....]
//每条线的信息
publicclassDrawData
{
privateList<int[]> _data;
privateint_lw;
privatebyte_alpha;
privatestring_color;
/// <summary>
/// 线条信息
/// </summary>
publicList<int[]> data { get{ return_data; } set{ _data = value; } }
/// <summary>
/// 画笔宽
/// </summary>
publicintlw { get{ return_lw; } set{ _lw = value; } }
/// <summary>
/// 画笔透明度,C#下是0~255,需要转换一下
/// </summary>
publicbytealpha { get{ return(byte)Math.Floor(_alpha * 2.55); } set{ _alpha = value; } }
/// <summary>
/// 画笔颜色
/// </summary>
publicstringcolor { 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>
/// <returns></returns>
protectedPoint[] GetPoints(List<int[]> data, boolIsImg, inth, intw)
{
inttop = IsImg?25:0, bottom = top + h;
List<Point> points = newList<Point>();
foreach(int[] d indata)
{
if((IsImg && d[0] < w && d[1] >= top && d[1] <= bottom) || (!IsImg && d[0] < w && d[1] < h))
points.Add(newPoint(d[0], d[1]-top));//注意y要减去top当配置了img时,应为img加载位置离顶部25px的位置
}
returnpoints.ToArray();
}
publicvoidProcessRequest(HttpContext context)
{
stringimg = context.Request.Form["img"], w = context.Request.Form["w"], h = context.Request.Form["h"]
, drawdata = context.Request.Form["drawdata"]
, fn = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "."+ context.Request.Form["ext"];//新文件名
Regex rxInt = newRegex(@"^\d+$", RegexOptions.Compiled);
List<DrawData> data = (List<DrawData>)JsonConvert.DeserializeObject(drawdata, typeof(List<DrawData>));
Bitmap bm;
boolIsImg=false;
intintW, intH;
if(!string.IsNullOrEmpty(img) && File.Exists(context.Server.MapPath(img))){//存在图片
bm = newBitmap(context.Server.MapPath(img));
IsImg=true;
intW = bm.Width;
intH = bm.Height;
}
else
{
intW = rxInt.IsMatch(w) ? int.Parse(w) : 650;
intH = rxInt.IsMatch(h) ? int.Parse(h) : 400;
bm = newBitmap(intW, intH);
}
Color color = Color.White;
using(Graphics g = Graphics.FromImage(bm))
{
foreach(DrawData d indata)
{
color = Color.FromArgb(d.alpha, ColorTranslator.FromHtml("#"+ d.color));
using(Pen pen = newPen(color, d.lw))
{
g.DrawLines(pen, GetPoints(d.data, IsImg, intH, intW));
}
}
}
bm.Save(context.Server.MapPath(fn));
bm.Dispose();
context.Response.Write("{success:true,fn:'"+ fn + "'}");
}
publicboolIsReusable {
get{
returnfalse;
}
}
}