使用Jcrop实现图片上传、剪裁和保存(ASP.NET)
2012-02-12 20:54
1001 查看
Jcrop是一款jquery图片裁剪插件,可以实现图片在线裁剪,达到和图像软件处理的效果,界面和操作也相当的人性化,只需要拖曳鼠标即可完成,部署到服务器也非常简单,在网站建设过程中轻易美化表单,并且改善用户体验,本文是Jcrop的中文文档手册。
入门
•下载当前版本
•放到页面相应的位置
•同时也需要加载jquery
加载顺序
•jQuery.js
•Jcrop.js
•Jcrop CSS样式
如:
<script src="js/jquery.pack.js"></script>
<script src="js/jquery.Jcrop.pack.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
注意:你也可以调整成其他的位置
调用
假如:<img src="flowers.jpg" id="cropbox" />
编写以下脚本
<script language="Javascript">
jQuery(function() {
jQuery('#cropbox').Jcrop();
});
</script>
Jcrop就可以激活了
事件处理
Jcrop有2个主要的事件处理程序 onChange 和 onSelect.
onSelect callback 选择完成后调用
onChange callback 选框移动(或者说改变)时调用
定义一个事件出来函数
<script language="Javascript">
function showCoords(c)
{
// variables can be accessed here as
// c.x, c.y, c.x2, c.y2, c.w, c.h
};
</script>
然后附加上去
<script language="Javascript">
jQuery(function() {
jQuery('#cropbox').Jcrop({
onSelect: showCoords,
onChange: showCoords
});
});
</script>
这是一个标准的jquery语法,注意最好一个属性后面没有逗号
设置选项
参数名称 类型 描述 默认
aspectRatio decimal 设定宽高比 n/a
minSize array [ w, h ] 设置最小尺寸 n/a
maxSize array [ w, h ] 设置最大尺寸 n/a
setSelect array [ x, y, x2, y2 ] 设置一个初选框的位置 n/a
bgColor color value 设置背景容器颜色 'black'
bgOpacity decimal 0 - 1 设置当图像被裁剪选框外的透明度 .6
如:
<script language="Javascript">
jQuery(function() {
jQuery('#cropbox').Jcrop({
onSelect: showCoords,
bgColor: 'black',
bgOpacity: .4,
setSelect: [ 100, 100, 50, 50 ],
aspectRatio: 16 / 9
});
});
</script>
使用Jcrop实现图片上传、剪裁和保存(ASP.NET)
前段时间项目中使用到了Jcrop剪裁用户头像,费了不少的力气,今天我就做个Demo当作备忘,只是做个演示,细节方面暂不考虑哦。一、首先新建数据库PhotoDataBase,新建数据表Photo_tb,结构如下:
一、下载Jcrop包:http://deepliquid.com/content/Jcrop.html,里面包含了JS文件和几个Demo,你可以打开看看效果和它们的代码。
三、打开VS 2008,新建一个Web项目,名称自取。然后把Jcrop的三个JS和CSS文件拷贝到项目中,最终解决方案列表如下:
四、新建Default.aspx,其代码如下:
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></title>
<script src="JS/jquery.min.js" type="text/javascript"></script>
<script src="JS/jquery.Jcrop.js" type="text/javascript"></script>
<link href="CSS/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<link href="CSS/demos.css" rel="stylesheet" type="text/css" />
<script language="Javascript">
// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showCoords(c) {
jQuery('#x').val(c.x);
jQuery('#y').val(c.y);
jQuery('#x2').val(c.x2);
jQuery('#y2').val(c.y2);
jQuery('#w').val(c.w);
jQuery('#h').val(c.h);
};
$(function() {
$("#UploadPhoto").change(function() {
var location = "file:///" + $("#UploadPhoto").val();
var type = location.substr(location.lastIndexOf(".")).toLowerCase();
if (type == ".jpg" || type == ".gif" || type == ".jpeg" || type == ".bmp") {
var image = new Image();
image.dynsrc = location;
if (image.fileSize / 1024 > 1000) { alert("照片请不要大于1000KB"); }
else {
$("#cropbox").attr("src", location);
jQuery('#cropbox').Jcrop({
onChange: showCoords,
onSelect: showCoords
});
}
}
else {
alert("图片格式不对!");
}
})
});
</script>
</head>
<body>
<div id="outer">
<div class="jcExample">
<div class="article">
<h1>
Jcrop图片剪裁Demo</h1>
<!-- This is the image we're attaching Jcrop to -->
<img src='<%=(!string.IsNullOrEmpty(PhotoPath))?PhotoPath:"picture.aspx"%>' id="cropbox" style="width:600px;height:400px" />
<!-- This is the form that our event handler fills -->
<form runat="server">
<label>
X1
<input type="text" size="4" id="x" name="x" /></label>
<label>
Y1
<input type="text" size="4" id="y" name="y" /></label>
<label>
X2
<input type="text" size="4" id="x2" name="x2" /></label>
<label>
Y2
<input type="text" size="4" id="y2" name="y2" /></label>
<label>
W
<input type="text" size="4" id="w" name="w" /></label>
<label>
H
<input type="text" size="4" id="h" name="h" /></label>
<div>
<br />
<input type="file" id="UploadPhoto" name="UploadPhoto" />
<asp:Button ID="Button1" runat="server" Text="确认剪裁并保存"
onclick="Button1_Click" />
</div>
</form>
</div>
</div>
</div>
</body>
</html>
复制代码
注意:
是重点,如果在页面加载的时候就绑定这个事件的话,使用上传控件上传图片的时候,不能改变图片的显示。JCrop还有其他的一些设置,您可以查阅相关文档。
六、Default页面后台代码如下:
View
Code
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Web.UI;
public partial class Default : Page
{
public string PhotoPath;
protected void Page_Load(object sender, EventArgs e)
{
PhotoPath = Server.MapPath("Images/default.jpg");
}
protected void Button1_Click(object sender, EventArgs e)
{
int x = int.Parse(Request["x"]);
int y = int.Parse(Request["y"]);
int w = int.Parse(Request["w"]);
int h = int.Parse(Request["h"]);
string filename = Request["UploadPhoto"];
byte[] image = CropImage(filename, w, h, x, y);
if (image != null)
PhotoPath = "";
}
private byte[] CropImage(string originaImgPath, int width, int height, int x, int y)
{
byte[] CropImage = Crop(originaImgPath, width, height, x, y);
if (!SaveToDatabase(CropImage))
{
Response.Write("图像保存失败!");
}
return CropImage;
}
/// <summary>
/// 剪裁图像
/// </summary>
/// <param name="Img"></param>
/// <param name="Width"></param>
/// <param name="Height"></param>
/// <param name="X"></param>
/// <param name="Y"></param>
/// <returns></returns>
private byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (var OriginalImage = new Bitmap(Img))
{
using (var bmp = new Bitmap(Width, Height, OriginalImage.PixelFormat))
{
bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
using (Graphics Graphic = Graphics.FromImage(bmp))
{
Graphic.SmoothingMode = SmoothingMode.AntiAlias;
Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height,
GraphicsUnit.Pixel);
var ms = new MemoryStream();
bmp.Save(ms, OriginalImage.RawFormat);
return ms.GetBuffer();
}
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
/// <summary>
/// 保存图像到数据库
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
private bool SaveToDatabase(byte[] image)
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ToString());
if (conn.State == ConnectionState.Closed)
conn.Open();
var cmd = new SqlCommand("insert into Photo values(@imagevalue)", conn);
cmd.Parameters.AddWithValue("@imagevalue", image);
if (cmd.ExecuteNonQuery() > 0)
return true;
return false;
}
}
复制代码
七、新建一个picture.aspx页面用于输出从数据库中读取的image字段的值,就像我们使用验证码的效果一样,通过一个链接就可以输出图片了。
其页面代码如下:
View
Code
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class picture : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ToString());
if (conn.State == ConnectionState.Closed)
conn.Open();
using ( var cmd = new SqlCommand("select top 1 photo from Photo order by id desc", conn))
{
var getreader = cmd.ExecuteReader();
if (getreader != null && getreader.HasRows)
{
//读取数据
while (getreader.Read())
{
Response.ContentType = "image/Jpeg";
var image = (byte[]) getreader[0];
Response.BinaryWrite(image);
Response.End();
}
}
}
}
}
}
复制代码
八、运行效果如下:
九、最终提供Demo源码下载
http://files.cnblogs.com/yuananyun/Jcrop.rar
相关文章推荐
- 使用Jcrop实现图片上传、剪裁和保存(ASP.NET)
- ASP.NET z中使用crop实现图片上传、剪裁和保存
- ASP.NET使用Jcrop插件实现图片上传裁剪功能
- asp.net中使用Uploadify插件实现多张图片上传,上传后可显示缩略图、删除图片
- C# Asp.net使用FormData对象实现ajax提交表单及上传图片
- asp.net 自定义控件实现无刷新上传图片,立即显示缩略图,保存图片缩略图
- Asp.net Mvc中使用uploadify实现图片缩放保存
- asp.net 自定义控件实现无刷新上传图片,立即显示缩略图,保存图片缩略图
- Asp.net MVC使用swupload实现多图片上传功能
- ASP.NET 5探险(3):使用UMEditor并实现图片上传
- asp.net使用jquery.form实现图片异步上传
- 在asp.Net中使用fileuplod控件实现上传图片的功能
- ASP.NET MVC中使用Dropzone.js实现图片的批量拖拽上传
- asp.net 自定义控件实现无刷新上传图片,立即显示缩略图,保存图片缩略图
- 在asp.Net中使用fileuplod控件实现上传图片的功能
- 在ASP.NET项目中使用CKEditor +CKFinder实现图片上传功能
- ASP.NET项目中使用CKEditor +CKFinder 实现上传图片
- asp.net+js+ajax实现手机移动端页面预览、剪裁、上传头像图片
- ASP.NET项目中使用CKEditor +CKFinder 实现上传图片
- ASP.NET使用Jcrop实现头像在线编辑保存