asp.net+MVC3.0头像上传

 

 var SilderSetValue = function (i) {
var left
= parseInt($(".child").css("left"));
left
+= i;

if (left <0) {
left
=0;
}
if (left >200) {
left
=200;
}
scaleFactor
= Math.pow(factor, (left /72-1));
if (i < 0 && scaleFactor > 1) {//此处增加一个判断,防止第一次点击缩小的时候,得到的倍数大于1
scaleFactor = 0.99
;
}
if (scaleFactor < minFactor) {
scaleFactor
= minFactor;
}
if (scaleFactor > factor) {
scaleFactor
= factor;
}
var iconElement
= $("#ImageIcon");
var imagedrag
= $("#ImageDrag");

  

   针对图片第一次点击缩小,图片会变成放大效果,是因为scaleFactor 第一次得到的值大于1,所以此处做个判断,如果点击缩小,并且scaleFactor 大于1的情况下,把scaleFactor(缩小倍数)修改成0.99,此处数字任意,但是必须大于0.88
此处图片大小是设置189*189,之前版本是120*120.如果想设置任意大小只需要把代码中的 189替换成要设置的数字
同时main.css也得修改,把画布大小和头像大小调整即可
 
忙了一个星期才整出来,辛苦了,是一周的中午都没有休息换来的啊,~~~~(>_<)~~~~ 
View下UploadImg.cshtml
View Code
<link href="http://www.cnblogs.com/css/main.css" type="text/css" rel="Stylesheet"/>
<script src="http://www.cnblogs.com/Scripts/jquery1.2.6.pack.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.cnblogs.com/Scripts/jquery.easydrag.js"></script>
<script type="text/javascript" src="http://www.cnblogs.com/Scripts/CutPic.js"></script>
<script type="text/javascript" src="http://www.cnblogs.com/Scripts/common.js"></script>
<script type="text/javascript">
// function Step1() {
// $("#Step2Container").hide();
// }
// function Step2() {
// $("#CurruntPicContainer").hide();
// }
// function Step3() {
// $("#Step2Container").hide();
// }
</script>
<script type="text/javascript">
function btn_Upload() {
ajaxRequest(
"/home/UploadImg", null);
}
function btn_Save() {
var url
="/home/SaveHead";
var postData
="&imgurl="+ $('#imgurl').val() +"&img_width="+ $('#img_width').val() +"&img_height="+ $('#img_height').val() +"&img_top="+ $('#img_top').val() +"&img_left="+ $('#img_left').val() +"&img_dropwidth="+ $('#img_dropwidth').val() +"&img_dropheight="+ $('#img_dropheight').val() +"&img_zoom="+ $('#img_zoom').val();
var result
= ajaxRequest(url, postData);
if (result !="") {
document.getElementById(
"imgphoto").setAttribute("src", result+"?"+Math.random());
alert(
"头像保存成功!");
}
}
function btn_Cancel()
{
$(
"#ImageIcon").hide();
}
</script>
<form id="form1" method="post" action="UploadImg" enctype="multipart/form-data">
<div style="width:740px; margin:0px auto">
<input type="hidden" id="imgurl" value="@ViewBag.SUserHeadImgUrl"/>
<div class="left">
<!--Step 2-->
<div id="Step2Container">
<div class="title">
裁切头像照片
</div>
<div class="uploadtooltip">您可以拖动照片以裁剪满意的头像"</div>
<div id="Canvas"class="uploaddiv">
<table id="Crop" cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<td style="height: 73px" colspan="3"class="Overlay"></td>
</tr>
<tr>
<td style="width: 82px"class="Overlay"></td>
<td style="width: 189px;height:189px; border:solid 1px white;"></td>
<td style="width: 82px"class="Overlay"></td>
</tr>
<tr>
<td style="height: 73px" colspan="3"class="Overlay"></td>
</tr>
</tbody>
</table>
<div id="IconContainer" style="position:relative;top:0px;left:0px;">
@if (
!string.IsNullOrEmpty(ViewBag.SUserHeadImgUrl))
{
<img src="@ViewBag.SUserHeadImgUrl?${requestScope.random}" id="ImageIcon" style="border:0px; position: relative;"/>
<img src="@ViewBag.SUserHeadImgUrl?${requestScope.random}" id="ImageDrag" style="border:0px; position: relative;display:none;"/>
}
</div>
</div>
<div class="uploaddiv">
<table>
<tbody>
<tr>
<td id="Min">
<img alt="缩小" src="../images/Minc.gif" id="moresmall"class="smallbig"/>
</td>
<td>
<div id="bar">
<div id="barchild"class="child"></div>
</div>
</td>
<td id="Max">
<img alt="放大" src="../images/c.gif" id="morebig"class="smallbig"/>
</td>
</tr>
</tbody>
</table>
</div>
<div class="uploaddiv">
<input type="button" id="btn_Image" value="保存" onclick="btn_Save()"/>
<input type="button" id="btn_Image" value="取消" onclick="btn_Cancel()"/>
</div>
<div>
<input type="text" id="img_width" value="1"/>
<input type="text" id="img_height" value="1"/>
<input type="text" id="img_top" value="82"/>
<input type="text" id="img_left" value="73"/>
<input type="text" id="img_dropwidth" value="189"/>
<input type="text" id="img_dropheight" value="189"/>
<input type="text" id="img_zoom"/>
</div>
</div>
</div>
<div class="right">
<!--Step 1-->
<div id="Step1Container">
<div class="title">更换照片</div>
<div id="uploadcontainer">
<div class="uploadtooltip">
请选择新的照片文件,文件需小于2.5MB
</div>
<div class="uploaddiv">
<input name="additionalImgFile" type="file" size="20"/>
</div>
<div class="uploaddiv">
<input type="submit" value="上 传" onclick="btn_Upload()"/>
</div>
</div>
<!--当前照片-->
<div id="CurruntPicContainer">
<div class="title"><b>当前照片</b></div>
<div class="photocontainer">
@if (
!string.IsNullOrEmpty(ViewBag.SUserHeadImgUrl))
{
<img id="imgphoto" src="@ViewBag.UserHeadImgUrl?${requestScope.random}" width="189" height="189"/>
}
else
{
<img id="imgphoto" src="http://images.cnblogs.com/face-2.jpg" width="189" height="189"/>
}
</div>
</div>
</div>
</div>
</div>
</form>

Controllers下HomeControllers.cs

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Configuration;
using System.IO;
using FileHeadImage.Tools;
namespace FileHeadImage.Controllers
{
publicclass HomeController : Controller
{
privatestaticreadonlystring PRODUCTIMAGES = ConfigurationManager.AppSettings["PhotosImages"];//图片路径
privatestaticreadonlystring APPLICATIONPATH = System.AppDomain.CurrentDomain.BaseDirectory;//图片根目录

public ActionResult Index()
{
ViewBag.UserHeadImgUrl
="http://images.cnblogs.com/face-2.jpg";
return View();
}
#region 第一种上传图片
public ActionResult UploadImg()
{
// ViewBag.UserHeadImgUrl = "http://images.cnblogs.com/face-2.jpg";//如果没有头像,给页面设置一个默认头像,否则就读取默认值
return View();
}
//上传图片
[HttpPost]
public ActionResult UploadImg(HttpPostedFileBase additionalImgFile)
{
ViewBag.UserHeadImgUrl
="http://images.cnblogs.com/face-2.jpg";
#region 头像上传
bool flagUploadFile =true;
if (additionalImgFile !=null&&!string.IsNullOrEmpty(additionalImgFile.FileName))//修改图片
{
string imgUrl =string.Empty;
flagUploadFile
= Tool.UploadFileToServer(Tool.UploadingFileType.Image, additionalImgFile, PRODUCTIMAGES, "20110727head", out imgUrl);
if (flagUploadFile)
{
ViewBag.SUserHeadImgUrl
= PRODUCTIMAGES + imgUrl;
}
else
{
Response.Write(
string.Format("<script type='text/javascript'>alert('上传图片失败!');history.go(-1);</script>"));
return View();
}
}
#endregion
return View();
}
//裁剪图片
publicstring SaveHead(string imgurl, int img_width =0, int img_height =0, int img_top =0, int img_left =0, int img_dropwidth =0, int img_dropheight =0, int img_zoom =0)
{
try
{
string sFilePath =APPLICATIONPATH+ PRODUCTIMAGES+"small.jpg";
string middleFilePath ="middle.jpg";
string middlefilename = Tool.SaveCutPic(APPLICATIONPATH + imgurl, Server.MapPath(PRODUCTIMAGES), 0, 0, 189,
189, img_left, img_top, img_width, img_height,middleFilePath);//裁剪中图片
Tool.MakeThumbnail(APPLICATIONPATH+PRODUCTIMAGES + middlefilename, sFilePath, 50, 50, "HW");//小图片
return PRODUCTIMAGES + middlefilename;
}
catch
{
return"";
}
}
#endregion
}
}

Tools文件下Tools.cs

View Code
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace FileHeadImage.Tools
{
publicstaticclass Tool
{
privatestaticreadonlystring APPLICATIONPATH = System.AppDomain.CurrentDomain.BaseDirectory;

publicstaticstring GetGuid()
{
return Guid.NewGuid().ToString().Replace("-", "").ToUpper();
}
#region 上传图片、文件代码
privatedelegatebool FileIsValidHandler(string suffix);
publicenum UploadingFileType
{
Docuemnt,
Image
}
privatestaticbool ImageFileIsValid(string suffix)
{
switch (suffix)
{
case"jpg":
returntrue;
case"jpeg":
returntrue;
case"bmp":
returntrue;
case"gif":
returntrue;
case"png":
returntrue;
default:
returnfalse;
}
}
privatestaticbool DocumentFileIsValid(string suffix)
{
switch (suffix)
{
case"xls":
returntrue;
case"ppt":
returntrue;
case"doc":
returntrue;
case"xlsx":
returntrue;
case"pptx":
returntrue;
case"docx":
returntrue;
case"pdf":
returntrue;
case"txt":
returntrue;
case"rar":
returntrue;
default:
returnfalse;
}
}
privatestaticbool FileIsValid(string suffix, FileIsValidHandler handler)
{
return handler(suffix);
}
///<summary>
/// 删除图片或者文件
///</summary>
publicstaticbool DeleteFile(string filename, string virtualPath)
{
string filePath = APPLICATIONPATH +@"\"+ virtualPath +@"\"+ filename;
try
{
if (File.Exists(filePath))
File.Delete(filePath);
returntrue;
}
catch (Exception ex)
{
throw ex;
}
}
///<summary>
/// 文件存储
///</summary>
publicstaticbool UploadFileToServer(UploadingFileType type, HttpPostedFileBase file, string virtualPath, string id, outstring newFileName)
{
newFileName
=string.Empty;
if (file !=null&&!string.IsNullOrEmpty(file.FileName) && file.ContentLength <=5000000)
{
bool flag = ValidateFileAndGetName(type, file, id, out newFileName);
if (flag)
{
string filePath = APPLICATIONPATH + virtualPath +@"\"+ newFileName;
file.SaveAs(filePath);
}
return flag;
}

returnfalse;
}
///<summary>
/// 文件存储
///</summary>
publicstaticbool UploadImageToServer(UploadingFileType type, HttpPostedFileBase file, string virtualPath, string id, int ImageWidth, int ImageHeight, outstring newFileName)
{
newFileName
=string.Empty;
if (file !=null&&!string.IsNullOrEmpty(file.FileName) && file.ContentLength <=5000000)
{
bool flag = ValidateFileAndGetName(type, file, id, out newFileName);
if (flag)
{
string filePath = APPLICATIONPATH + virtualPath +@"\"+ newFileName;
string sFilePath = APPLICATIONPATH + virtualPath +@"\s_"+ newFileName;
file.SaveAs(filePath);
if (type != UploadingFileType.Docuemnt)
MakeThumbnail(filePath, sFilePath, ImageWidth, ImageHeight,
"HW");
}
return flag;
}

returnfalse;
}
///<summary>
/// 验证上传文件是否合法并设置获取新的文件名
///</summary>
privatestaticbool ValidateFileAndGetName(UploadingFileType type, HttpPostedFileBase file, string id, outstring newFileName)
{
id
=string.IsNullOrEmpty(id) ? GetGuid() : id;
int index = file.FileName.LastIndexOf(".");
string suffix = file.FileName.Substring(index +1).Trim().ToLower();
newFileName
=string.Format("{0}.{1}", id, suffix);

switch (type)
{
case UploadingFileType.Docuemnt:
return FileIsValid(suffix, DocumentFileIsValid);
case UploadingFileType.Image:
return FileIsValid(suffix, ImageFileIsValid);
default:
returnfalse;
}
}
/// 生成缩略图
///</summary>
///<param name="originalImagePath">源图路径(物理路径)</param>
///<param name="thumbnailPath">缩略图路径(物理路径)</param>
///<param name="width">缩略图宽度</param>
///<param name="height">缩略图高度</param>
///<param name="mode">生成缩略图的方式</param>
publicstaticvoid MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
System.Drawing.Image originalImage
= System.Drawing.Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;

int x =0;
int y =0;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case"HW"://指定高宽缩放(可能变形)
break;
case"W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case"H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case"Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh
= originalImage.Height;
ow
= originalImage.Height * towidth / toheight;
y
=0;
x
= (originalImage.Width - ow) /2;
}
else
{
ow
= originalImage.Width;
oh
= originalImage.Width * height / towidth;
x
=0;
y
= (originalImage.Height - oh) /2;
}
break;
default:
break;
}

//新建一个bmp图片
System.Drawing.Image bitmap =new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
/// 裁剪图片后生成缩略图
///</summary>
///<param name="originalImagePath">源图路径(物理路径)</param>
///<param name="thumbnailPath">缩略图路径(物理路径)</param>
///<param name="x">缩略图宽度</param>
///<param name="y">缩略图高度</param>
///<param name="w">缩略图宽度</param>
///<param name="h">缩略图高度</param>
///<param name="mode">生成缩略图的方式 Cut表示裁剪,此处用裁剪Cut</param>
publicstaticvoid MakeThumbnail(string originalImagePath, string thumbnailPath,int x,int y,int w,int h, string mode)
{
System.Drawing.Image originalImage
= System.Drawing.Image.FromFile(originalImagePath);
int towidth = w;
int toheight = h;
int ow = originalImage.Width;
int oh = originalImage.Height;

switch (mode)
{
case"HW"://指定高宽缩放(可能变形)
break;
case"W"://指定宽,高按比例
toheight = originalImage.Height * w / originalImage.Width;
break;
case"H"://指定高,宽按比例
towidth = originalImage.Width * h / originalImage.Height;
break;
case"Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh
= originalImage.Height;
ow
= originalImage.Height * towidth / toheight;
y
=0;
x
= (originalImage.Width - ow) /2;
}
else
{
ow
= originalImage.Width;
oh
= originalImage.Width * h / towidth;
x
=0;
y
= (originalImage.Height - oh) /2;
}
break;
default:
break;
}

//新建一个bmp图片
System.Drawing.Image bitmap =new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
#endregion
View Code
#region 裁剪图片
/// 裁剪图片后生成缩略图
///</summary>
///<param name="originalImagePath">源图路径(物理路径)</param>
///<param name="thumbnailPath">缩略图路径(物理路径)</param>
///<param name="x">缩略图宽度</param>
///<param name="y">缩略图高度</param>
///<param name="w">缩略图宽度</param>
///<param name="h">缩略图高度</param>
///<param name="mode">生成缩略图的方式 Cut表示裁剪,此处用裁剪Cut</param>
publicstaticstring MakeThumbnailCut(string originalImagePath, string thumbnailPath, int x, int y, int w, int h, string mode)
{
System.Drawing.Image originalImage
= System.Drawing.Image.FromFile(originalImagePath);
int towidth = w;
int toheight = h;
int ow = originalImage.Width;
int oh = originalImage.Height;
string filename ="small.jpg";
string filePath = thumbnailPath +"\\"+ filename;
switch (mode)
{
case"HW"://指定高宽缩放(可能变形)
break;
case"W"://指定宽,高按比例
toheight = originalImage.Height * w / originalImage.Width;
break;
case"H"://指定高,宽按比例
towidth = originalImage.Width * h / originalImage.Height;
break;
case"Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh
= originalImage.Height;
ow
= originalImage.Height * towidth / toheight;
y
=0;
x
= (originalImage.Width - ow) /2;
}
else
{
ow
= originalImage.Width;
oh
= originalImage.Width * h / towidth;
x
=0;
y
= (originalImage.Height - oh) /2;
}
break;
default:
break;
}

//新建一个bmp图片
System.Drawing.Image bitmap =new System.Drawing.Bitmap(towidth, toheight);

//新建一个画板
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

//清空画布并以透明背景色填充
g.Clear(System.Drawing.Color.Transparent);

//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
new System.Drawing.Rectangle(x, y, ow, oh),
System.Drawing.GraphicsUnit.Pixel);

try
{
//以jpg格式保存缩略图
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
return filename;
}

///<summary>
/// 获取图片指定部分
///</summary>
///<param name="pPath">图片路径</param>
///<param name="pSavePath">保存路径</param>
///<param name="pPartStartPointX">目标图片开始绘制处的坐标X值(通常为)</param>
///<param name="pPartStartPointY">目标图片开始绘制处的坐标Y值(通常为)</param>
///<param name="pPartWidth">目标图片的宽度</param>
///<param name="pPartHeight">目标图片的高度</param>
///<param name="pOrigStartPointX">原始图片开始截取处的坐标X值</param>
///<param name="pOrigStartPointY">原始图片开始截取处的坐标Y值</param>
///<param name="pFormat">保存格式,通常可以是jpeg</param>
publicstaticstring SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight,string filename)
{
using (Image originalImg = Image.FromFile(pPath))
{
if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
{
return SaveCutPic(pPath, pSavedPath, pPartStartPointX, pPartStartPointY, pPartWidth, pPartHeight,
pOrigStartPointX, pOrigStartPointY);

}
//string filename ="small.jpg";
string filePath = pSavedPath +"\\"+ filename;

Bitmap thumimg
= MakeThumbnail(originalImg, imageWidth, imageHeight);

Bitmap partImg
=new Bitmap(pPartWidth, pPartHeight);

Graphics graphics
= Graphics.FromImage(partImg);
Rectangle destRect
=new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
Rectangle origRect =new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)

///文字水印
Graphics G = Graphics.FromImage(partImg);
//Font f = new Font("Lucida Grande", 6);
//Brush b = new SolidBrush(Color.Gray);
G.Clear(Color.White);
// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高质量、低速度呈现。
G.SmoothingMode = SmoothingMode.HighQuality;

graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
//G.DrawString("Xuanye", f, b, 0, 0);
G.Dispose();

originalImg.Dispose();
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
partImg.Save(filePath, ImageFormat.Jpeg);

partImg.Dispose();
thumimg.Dispose();
return filename;
}
}

publicstatic Bitmap MakeThumbnail(Image fromImg, int width, int height)
{
Bitmap bmp
=new Bitmap(width, height);
int ow = fromImg.Width;
int oh = fromImg.Height;

//新建一个画板
Graphics g = Graphics.FromImage(bmp);

//设置高质量插值法
g.InterpolationMode = InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);

g.DrawImage(fromImg,
new Rectangle(0, 0, width, height),
new Rectangle(0, 0, ow, oh),
GraphicsUnit.Pixel);

return bmp;

}

publicstaticstring SaveCutPic(string pPath, string pSavedPath, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY)
{
string filename = DateTime.Now.ToString("yyyyMMddHHmmss") +".jpg";
string filePath = pSavedPath +"\\"+ filename;

using (Image originalImg = Image.FromFile(pPath))
{
Bitmap partImg
=new Bitmap(pPartWidth, pPartHeight);
Graphics graphics
= Graphics.FromImage(partImg);
Rectangle destRect
=new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
Rectangle origRect =new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置(默认从原图中截取的图片大小等于目标图片的大小)

///注释 文字水印
Graphics G = Graphics.FromImage(partImg);
//Font f = new Font("Lucida Grande", 6);
//Brush b = new SolidBrush(Color.Gray);
G.Clear(Color.White);
// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
G.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高质量、低速度呈现。
G.SmoothingMode = SmoothingMode.HighQuality;

graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
//G.DrawString("Xuanye", f, b, 0, 0);
G.Dispose();

originalImg.Dispose();
if (File.Exists(filePath))
{
File.SetAttributes(filePath, FileAttributes.Normal);
File.Delete(filePath);
}
partImg.Save(filePath, ImageFormat.Jpeg);
partImg.Dispose();
}
return filename;
}
#endregion
}
}

Css文件下main.css

View Code
.left
{
float:left;
width:
48%;
}
.right
{
float:left;
width:
48%;
margin
-left:20px;
}
.title
{
border
-bottom:solid 1px #ccc;
font
-size:13px;
}
.photocontainer
{
margin
-top:10px;
width:208px;
height:208px;
background:url(
"../images/bg_120.gif") no-repeat left top;
padding:5px 13px 13px 5px;
}
.uploadtooltip
{
margin
-top:10px;
color: #
555;
line
-height:150%;
font
-size:12px;
}
.uploaddiv
{
margin
-top:10px;
}
input
{
padding:3px;
}
#Step2Container
{
/*display:none; */
}
#Canvas
{
position: relative;
width: 353px;
height: 335px;
border: 2px solid #
888;
overflow: hidden;
margin
-left: 4px;
cursor: pointer;
}
#Crop
{
position: relative;
width: 353px;
height: 335px;
z
-index: 7;
top: 0px;
left: 0px;
opacity:
0.75;
filter: alpha(opacity
=75);
}
.smallbig
{
cursor:pointer;
}
#bar
{
width: 211px;
height: 18px;
background
-image: url("../images/track.gif");
background
-repeat: no-repeat;
position: relative;
}
.child
{
width: 11px;
height: 16px;
background
-image: url("../images/grip.gif");
background
-repeat: no-repeat;
left:
0;top:2px;
position: absolute;
left:100px;
}
#IconContainer
{
z
-index:3;
}
.imagePhoto
{
border
-width:0px;
position:relative;
}

.Overlay
{
FILTER:alpha(opacity
=60);
opacity:
0.6;
background
-color:#ccc;
}

Scripts文件下Common.js

View Code
//初始化DatePicker控件
function initDatePicker(dateFrom, dateTo) {
$(
"#"+ dateFrom).datepicker();
$(
"#"+ dateTo).datepicker();
// Datepicker
$("#"+ dateFrom).datepicker("option", "dateFormat", "yy-mm-dd");
$(
"#"+ dateTo).datepicker("option", "dateFormat", "yy-mm-dd");
}

//DIV Display
function display(id, flag) {
document.getElementById(id).style.display
= flag ?"block" : "none";
}

// Close Open Windows
function closeWindow() {
window.opener
=null;
window.close();
}

//Ajax局部更新
function ajaxUpgrade(url,id) {
$.ajax({
type:
"POST",
url: url,
//data: postData,
success: function(data) {
//$("#" + id).html(data);
$("#"+ id).html(data);
}
});
}
function ajaxSyncUpgrade(url, id) {
$.ajax({
type:
"POST",
url: url,
async:
false,
success: function(data) {
//$("#" + id).html(data);
$("#"+ id).html(data);
}
});
}

//Ajax请求数据
function ajaxRequest(url, postData) {
var result;
$.ajax({
type:
"POST",
url: url,
data: postData,
async:
false,
success: function(data) {
result
= data;
}
});
return result;
}

//Ajax异步删除记录
function ajaxDelete(url) {
var result;
$.ajax({
type:
"POST",
url: url,
async:
false,
success: function(data) {
result
= data;
}
});
return result;
}

Scripts文件下CutPic.js

View Code
///<reference path="JSintellisense/jquery-1.2.6-intellisense.js" />
(function($) {
$.fn.noSelect
= function(p) { //no select plugin by me :-)
if (p ==null)
prevent
=true;
else
prevent
= p;

if (prevent) {

returnthis.each(function() {
if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function() { returnfalse; });
elseif ($.browser.mozilla) {
$(
this).css('MozUserSelect', 'none');
$(
'body').trigger('focus');
}
elseif ($.browser.opera) $(this).bind('mousedown', function() { returnfalse; });
else $(this).attr('unselectable', 'on');
});

}
else {


returnthis.each(function() {
if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
elseif ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
elseif ($.browser.opera) $(this).unbind('mousedown');
else $(this).removeAttr('unselectable', 'on');
});

}

};
//end noSelect
})(jQuery);

//全局变量定义
var CANVAS_WIDTH =284+2+69; //画布的宽
var CANVAS_HEIGHT =266+2+69; //画布的高
var ICON_WIDTH =189;
var ICON_HEIGHT
=189
var LEFT_EDGE
= (CANVAS_WIDTH - ICON_WIDTH) /2; //72
var TOP_EDGE = (CANVAS_HEIGHT - ICON_HEIGHT) /2; //83

var RIGHT_EDGE
= LEFT_EDGE + ICON_WIDTH;
var BOTTOM_EDGE
= TOP_EDGE + ICON_HEIGHT;

var CANVAS_LEFT_MARGIN
=4;

var CROP_LEFT
= LEFT_EDGE;
var CROP_TOP
=-BOTTOM_EDGE;

//用document. ready事件中在上传后第一次转向时无法获取到图片的打开,应该是没有被下载来的缘故
$(window).load(function () {
$(
"#Crop").noSelect();
var $iconElement
= $("#ImageIcon");
var $imagedrag
= $("#ImageDrag");

//获取上传图片的实际高度,宽度
var image =new Image();
image.src
= $iconElement.attr("src");
var realWidth
= parseInt(CANVAS_WIDTH);
var realHeight
= parseInt(CANVAS_HEIGHT);
image
=null;

//计算缩放比例开始
var minFactor = Math.max(ICON_WIDTH / realWidth, ICON_HEIGHT / realHeight)
if (ICON_WIDTH > realWidth && ICON_HEIGHT > realHeight) {
minFactor
=1;
}
// var factor = minFactor > 0.25 ? 8.0 : 4.0 / Math.sqrt(minFactor);
var factor =3;
//图片缩放比例 此处明天需要调整
var scaleFactor =1;
if (realWidth > CANVAS_WIDTH && realHeight > CANVAS_HEIGHT) {
if (realWidth / CANVAS_WIDTH > realHeight / CANVAS_HEIGHT) {
scaleFactor
= CANVAS_HEIGHT / realHeight;
}
else {
scaleFactor
= CANVAS_WIDTH / realWidth;
}
}
//计算缩放比例结束

//设置滑动条的位置,设置滑动条的值的变化来改变缩放率是一个非线性的变化,而是幂函数类型 即类似y=factor(X)--此处x为幂指数
//此处100 * (Math.log(scaleFactor * factor) / Math.log(factor)) 为知道y 求解x 的算法
$("#barchild").css("left", 100* (Math.log(scaleFactor * factor) / Math.log(factor)) +"px");

//图片实际尺寸,并近似到整数
var currentWidth = Math.round(scaleFactor * realWidth);
var currentHeight
= Math.round(scaleFactor * realHeight);


//图片相对CANVAS的初始位置,图片相对画布居中
var originLeft = Math.round((CANVAS_WIDTH - currentWidth) /2);
var originTop
= Math.round((CANVAS_HEIGHT - currentHeight) /2- CANVAS_HEIGHT);

//计算截取框中的图片的位置
var dragleft = originLeft - LEFT_EDGE;
var dragtop
= originTop - TOP_EDGE + CANVAS_HEIGHT;
//设置图片当前尺寸和位置
$iconElement.css({ width: currentWidth +"px", height: currentHeight +"px", left: originLeft +"px", top: originTop +"px" });


//初始化默认值
$("#img_width").val(currentWidth);
$(
"#img_height").val(currentHeight);
$(
"#img_top").val(0- dragtop);
$(
"#img_left").val(0- dragleft);
$(
"#img_zoom").val(scaleFactor);

var oldWidth
= currentWidth;
var oldHeight
= currentHeight;

//设置图片可拖拽
$iconElement.easydrag(false).setHandler("Crop").ondrag(function (e, target) {
var pos
= $(target).position();

$(
"#img_left").val(0- (parseInt(pos.left) - LEFT_EDGE));
$(
"#img_top").val(0- (parseInt(pos.top) - TOP_EDGE + CANVAS_HEIGHT));
}
);
$(
"#barchild").easydrag(false, "x").ondrag(function (e, target) {
var me
= $(target);
var left
= parseInt(me.css("left"));
if (left <0) {
left
=0;
me.css(
"left", 0);
}
if (left >200) {
me.css(
"left", 200);
}

//前面讲过了y=factor(x),此处是知道x求y的值,即知道滑动条的位置,获取缩放率
scaleFactor = Math.pow(factor, (left /100-1));
if (scaleFactor < minFactor) {
scaleFactor
= minFactor;
}
if (scaleFactor > factor) {
scaleFactor
= factor;
}
//以下代码同初始化过程,因为用到局部变量所以没有
var iconElement = $("#ImageIcon");
var imagedrag
= $("#ImageDrag");

var image
=new Image();
image.src
= iconElement.attr("src");
var realWidth
= parseInt(CANVAS_WIDTH);
var realHeight
= parseInt(CANVAS_HEIGHT);
image
=null;

//图片实际尺寸
var currentWidth = Math.round(scaleFactor * realWidth);
var currentHeight
= Math.round(scaleFactor * realHeight);

//图片相对CANVAS的初始位置
var originLeft = parseInt(iconElement.css("left"));
var originTop
= parseInt(iconElement.css("top"));

if (currentWidth > oldWidth) {
originLeft
-= Math.round((currentWidth - oldWidth) /2);
originTop
-= Math.round((currentHeight - oldHeight) /2);
}
else {
originLeft
+= Math.round((oldWidth - currentWidth) /2);
originTop
+= Math.round((oldHeight - currentHeight) /2);
}

dragleft
= originLeft - LEFT_EDGE;
dragtop
= originTop - TOP_EDGE + CANVAS_HEIGHT;

//图片当前尺寸和位置
iconElement.css({ width: currentWidth +"px", height: currentHeight +"px", left: originLeft +"px", top: originTop +"px" });

$(
"#img_zoom").val(scaleFactor);
$(
"#img_left").val(0- dragleft);
$(
"#img_top").val(0- dragtop);
if (currentWidth <=189) {
currentWidth
=189;
}
if (currentHeight <=189) {
currentHeight
=189;
}
$(
"#img_width").val(currentWidth);
$(
"#img_height").val(currentHeight);
oldWidth
= currentWidth;
oldHeight
= currentHeight;

});
var SilderSetValue
= function (i) {
var left
= parseInt($(".child").css("left"));
left
+= i;

if (left <0) {
left
=0;
}
if (left >200) {
left
=200;
}
scaleFactor
= Math.pow(factor, (left /72-1));
if (i <0&& scaleFactor >1) {
scaleFactor
=0.99;
}
if (scaleFactor < minFactor) {
scaleFactor
= minFactor;
}
if (scaleFactor > factor) {
scaleFactor
= factor;
}
var iconElement
= $("#ImageIcon");
var imagedrag
= $("#ImageDrag");

var image
=new Image();
image.src
= iconElement.attr("src");
var realWidth
= parseInt(CANVAS_WIDTH);
var realHeight
= parseInt(CANVAS_HEIGHT);
image
=null;

//图片实际尺寸
var currentWidth = Math.round(scaleFactor * realWidth);
var currentHeight
= Math.round(scaleFactor * realHeight);

//图片相对CANVAS的初始位置
var originLeft = parseInt(iconElement.css("left"));
var originTop
= parseInt(iconElement.css("top"));

if (currentWidth > oldWidth) {
originLeft
-= Math.round((currentWidth - oldWidth) /2);
originTop
-= Math.round((currentHeight - oldHeight) /2);
}
else {
originLeft
+= Math.round((oldWidth - currentWidth) /2);
originTop
+= Math.round((oldHeight - currentHeight) /2);
}
dragleft
= originLeft - LEFT_EDGE;
dragtop
= originTop - TOP_EDGE + CANVAS_HEIGHT;

//图片当前尺寸和位置
$("#barchild").css("left", left +"px");
iconElement.css({ width: currentWidth
+"px", height: currentHeight +"px", left: originLeft +"px", top: originTop +"px" });

$(
"#img_Zoom").val(scaleFactor);
$(
"#img_left").val(0- dragleft);
$(
"#img_top").val(0- dragtop);
$(
"#img_width").val(currentWidth);
$(
"#img_height").val(currentHeight);

oldWidth
= currentWidth;
oldHeight
= currentHeight;
}
//点击加减号
$("#moresmall").click(function () {
SilderSetValue(
-20);
});
$(
"#morebig").click(function () {
SilderSetValue(
20);
});

});

Scripts文件下jquery.easydrag.js

View Code
/**
* EasyDrag 1.5 - Drag & Drop jQuery Plug-in
*
* Thanks for the community that is helping the improvement
* of this little piece of code.
*
* For usage instructions please visit
http://fromvega.com/scripts
*/

(function($) {

// to track if the mouse button is pressed
var isMouseDown =false;

// to track the current element being dragged
var currentElement =null;
var Direction
= [];
// callback holders
var dropCallbacks = {};
var dragCallbacks
= {};

// bubbling status
var bubblings = {};

// global position records
var lastMouseX;
var lastMouseY;
var lastElemTop;
var lastElemLeft;

// track element dragStatus
var dragStatus = {};

// if user is holding any handle or not
var holdingHandler =false;

// returns the mouse (cursor) current position
$.getMousePosition = function(e) {
var posx
=0;
var posy
=0;

if (!e) var e = window.event;

if (e.pageX && e.pageY) {
posx
= e.pageX;
posy
= e.pageY;
}
elseif (e.clientX && e.clientY) {
posx
= e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy
= e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}

return { 'x': posx, 'y': posy };
};

// updates the position of the current element being dragged
$.updatePosition = function(e) {
var pos
= $.getMousePosition(e);
var spanX
= (pos.x - lastMouseX);
var spanY
= (pos.y - lastMouseY);
if (Direction[currentElement.id] =="all") {
$(currentElement).css(
"left", (lastElemLeft + spanX));
$(currentElement).css(
"top", (lastElemTop + spanY));
}
elseif (Direction[currentElement.id] =="x") {
$(currentElement).css(
"left", (lastElemLeft + spanX));
}
else {
$(currentElement).css(
"top", (lastElemTop + spanY));
}
};

// when the mouse is moved while the mouse button is pressed
$(document).mousemove(function(e) {
if (isMouseDown && dragStatus[currentElement.id] !='false') {
$.updatePosition(e);
if (dragCallbacks[currentElement.id] != undefined) {
dragCallbacks[currentElement.id](e, currentElement);
}
returnfalse;
}
});

// when the mouse button is released
$(document).mouseup(function(e) {
if (isMouseDown && dragStatus[currentElement.id] !='false') {
isMouseDown
=false;
if (dropCallbacks[currentElement.id] != undefined) {
dropCallbacks[currentElement.id](e, currentElement);
}

returnfalse;
}
});

// register the function to be called while an element is being dragged
$.fn.ondrag = function(callback) {
returnthis.each(function() {
dragCallbacks[
this.id] = callback;
});
};

// register the function to be called when an element is dropped
$.fn.ondrop = function(callback) {
returnthis.each(function() {
dropCallbacks[
this.id] = callback;
});
};

// disable the dragging feature for the element
$.fn.dragOff = function() {
returnthis.each(function() {
dragStatus[
this.id] ='off';
});
};

// enable the dragging feature for the element
$.fn.dragOn = function() {
returnthis.each(function() {
dragStatus[
this.id] ='on';
});
};

// set a child element as a handler
$.fn.setHandler = function(handlerId) {
returnthis.each(function() {
var draggable
=this;

// enable event bubbling so the user can reach the handle
bubblings[this.id] =true;

// reset cursor style
$(draggable).css("cursor", "");

// set current drag status
dragStatus[draggable.id] ="handler";

// change handle cursor type
$("#"+ handlerId).css("cursor", "move");

// bind event handler
$("#"+ handlerId).mousedown(function(e) {
holdingHandler
=true;
$(draggable).trigger(
'mousedown', [e]);
});

// bind event handler
$("#"+ handlerId).mouseup(function(e) {
holdingHandler
=false;
});
});
}

// set an element as draggable - allowBubbling enables/disables event bubbling
$.fn.easydrag = function(allowBubbling, direction) {

returnthis.each(function() {

// if no id is defined assign a unique one
if (undefined ==this.id ||!this.id.length) this.id ="easydrag"+ (new Date().getTime());

Direction[
this.id] = direction ||"all";
// save event bubbling status
bubblings[this.id] = allowBubbling ?true : false;

// set dragStatus
dragStatus[this.id] ="on";

// change the mouse pointer
$(this).css("cursor", "move");

// when an element receives a mouse press
$(this).mousedown(function(e, b) {
if (!b) {
b
= e;
}
// just when "on" or "handler"
if ((dragStatus[this.id] =="off") || (dragStatus[this.id] =="handler"&&!holdingHandler))
return bubblings[this.id];

// set it as absolute positioned
$(this).css("position", "absolute");

// set z-index
$(this).css("z-index", parseInt(new Date().getTime() /1000));

// update track variables
isMouseDown =true;
currentElement
=this;
// retrieve positioning properties
var pos = $.getMousePosition(b);
lastMouseX
= pos.x;
lastMouseY
= pos.y;

lastElemTop
=this.offsetTop;
lastElemLeft
=this.offsetLeft;

$.updatePosition(b);

return bubblings[this.id];
});
});
};

})(jQuery);

Webconfig.cs配置

View Code
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="true"/>
<add key="PhotosImages" value="/BabyPhotos/8a43c8b0d7ba4819b043257b37562c1e/"/>
</appSettings>

用到的jquery插件自己去下载 jquery-1.5.1.min.js 或者 jquery1.2.6.pack.js

images文件下图片:

  bg_120.gif

blank.jpg

face-2.jpg

c.gif

grip(11 16).gif

h.gif

man_bg.gif

Maxc.gif

Minc.gif

Minh.gif

track.gif

 

  

 

  

  

  

  

 

 

posted on 2011-08-30 11:39  落叶十九  阅读(63)  评论(0)    收藏  举报