实现这个功能主要用到了JQuery和基于JQuery的图片处理插件JCrop。
JQuery可以下载下来,或者在代码中这样引用<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>。
JCrop需要下载,其中还包括相应的一些例子可以作为参考。
这个例子有三部分功能,一、图片上传,二、现实用户上传上来的图片,三、图片剪裁。
主要的流程是:用户上传图片,显示图片,在用户点击剪裁按钮之后,用ajax的方式显示剪裁之后的图片。
上传图片就用的ASP.NET自带的文件上传控件,整个文件上传功能放在一个用户空间里面。
每次用户上传了图片以后,文件存放的位置持久化在一个xml文件中。
在用JCrop实现剪裁功能的时候,需要在页面中添加一些隐藏域来
存储图片剪裁中用到的坐标和宽高等数据。剪裁则用JQuery的Ajax功能实现。
)
<script src="../Scripts/jquery.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.Jcrop.js" type="text/javascript"></script>
<link href="../Style/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
<link href="../Style/demos.css" rel="stylesheet" type="text/css" />
然后我们需要添加调用JCrop的代码来实现图片的剪裁
<script type="text/javascript" language="Javascript">
jQuery(document).ready(function() {
jQuery('#cropbox').Jcrop({
onSelect: showCoords
});
});
function onCropClick() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ pPartStartPointX: '" + $('#x').val() + "', pPartStartPointY: '" + $('#y').val() + "', pPartWidth: '" + $('#w').val() + "', pPartHeight: '" + $('#h').val() + "'}",
url: "Default.aspx/CroppedImage",
dataType: "json",
success: function(data) {
$('#disp').html("<img src='" + data.d + "' alt='' />");
}
});
}
function showCoords(c) {
jQuery('#x').val(c.x);
jQuery('#y').val(c.y);
jQuery('#w').val(c.w);
jQuery('#h').val(c.h);
};
</script>
using System;
using System.Web;
using System.Web.Services;
[WebMethod]
public static string CroppedImage(int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight)
{
XmlHelper xmlHelper = new XmlHelper();
xmlHelper.XmlPath = HttpContext.Current.Server.MapPath("~/App_Data/ImagePaths.xml");
string originalPath = xmlHelper.GetImagepath();
string savePath = HttpContext.Current.Server.MapPath("~/Images/CropImg/");
string filename = ImageHelper.CropImage(originalPath, savePath, pPartWidth, pPartHeight, pPartStartPointX, pPartStartPointY);
string fullpath = "../Images/CropImg/" + filename;
return fullpath;
}
using System;
using System.Web.UI.HtmlControls;
public partial class Controls_ImageUpload : System.Web.UI.UserControl
{
private readonly string IMG_PATH = "~/Images/Upload/";
private XmlHelper _xmlHelper = new XmlHelper();
/// <summary>
/// Name of a control to operate
/// </summary>
public string ControlName { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetPathInfo();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
// Specify the path on the server to
// save the uploaded file to.
String savePath = Server.MapPath(IMG_PATH);
// Before attempting to perform operations
// on the file, verify that the FileUpload
// control contains a file.
if (imgUpload.HasFile)
{
// Get the name of the file to upload.
String fileName = imgUpload.FileName;
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
imgUpload.SaveAs(savePath);
_xmlHelper.XmlPath = Server.MapPath("~/App_Data/ImagePaths.xml");
_xmlHelper.StoreImagePath(savePath);
SetPathInfo();
}
}
catch (Exception)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Image can not be uploaded, please check!'", true);
}
}

private void SetPathInfo()
{
string serverPath = "~/Images/Upload/";
XmlHelper xmlHelper = new XmlHelper();
xmlHelper.XmlPath = Server.MapPath("~/App_Data/ImagePaths.xml");
string imgPath = xmlHelper.GetImagepath();
string filename = GetFileName(imgPath);
serverPath += filename;
HtmlImage cropbox = (HtmlImage)Parent.FindControl("cropbox");
if (cropbox != null)
cropbox.Src = serverPath;
HtmlImage preview = (HtmlImage)Parent.FindControl("preview");
if (preview != null)
preview.Src = serverPath;
Context.Items["imgsrc"] = serverPath;
}
private string GetFileName(string fullname)
{
// Validation of string is not implemented temperarily
int index = fullname.LastIndexOf("\\");
string filename = fullname.Substring(index + 1);
return filename;
}
}
public void StoreImagePath(string img)
{
try
{
if (_xdoc == null)
{
_xdoc = XDocument.Load(XmlPath);
}
_xdoc.Root.Descendants().Remove();
_xdoc.Root.Add(new XElement("path", img));
_xdoc.Save(this.XmlPath);
}
catch
{
throw new Exception("Error occured in adding image path.");
}
}
public string GetImagepath()
{
string imagePath = string.Empty;
try
{
if (_xdoc == null)
{
_xdoc = XDocument.Load(XmlPath);
}
imagePath = _xdoc.Root.Descendants().First().Value.ToString();
}
catch
{
throw new Exception("Error occured in getting image path.");
}
return imagePath;
}
public static string CropImage(string originamImgPath, string imgPath, int width, int height, int x, int y)
{
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
byte[] CropImage = Crop(originamImgPath, width, height, x, y);
using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
{
ms.Write(CropImage, 0, CropImage.Length);
using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
{
string SaveTo = imgPath + filename;
CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
}
}
return filename;
}
private static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (Image OriginalImage = Image.FromFile(Img))
{
using (Bitmap 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);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, OriginalImage.RawFormat);
return ms.GetBuffer();
}
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛