Asp.Net Mvc3 实现图片上传+图片剪切(uploadify+Jcrop)

  最近开发项目中,实现了头像上传、裁剪功能,头像上传使用的是Uploadify Js,剪切图片使用的是Jcrop插件,现在有空整理了一下,下面进行说明:

  Uploadify 插件的介绍地址:http://www.uploadify.com/documentation/

  Jcrop 插件的介绍地址:http://deepliquid.com/content/Jcrop.html  中文API 地址:http://www.kmwzjs.com/site/p-view52.html

Js处理代码:

<script type="text/javascript">
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};

function BeginJcrop() {
$('#TestImage').Jcrop({
aspectRatio: 1,
maxSize: [200, 200],
minSize: [50, 50],
minSelect: [50, 50],
setSelect: [5, 5, 105, 105],
onChange: updateCoords,
onSelect: updateCoords
});

}

$(document).ready(function () {
var isupload = false;
$("#btnCut").click(function () {
if (isupload == false) {
alert("请选择头像");
return;
}
$('#btnCut').lock();
$.ajax({
url: '/Demo/Cut?v=' + Math.random(),
data: { xstr: $("#x").val(), ystr: $("#y").val(), wstr: $("#w").val(), hstr: $("#h").val(), 'imageName': $("#imageName").val() },
datatype: "text/json",
type: 'post',
success: function (data) {
if (data == true) {
$('#btnCut').unlock();
var t_url = "/Uploads/Space/Photo/";
$("#imgBig").attr("src", "");
$("#imgNormal").attr("src", "");
$("#imgSmall").attr("src", "");
$("#imgBig").attr("src", t_url + "Photo_big.jpg?v=" + Math.random());
$("#imgNormal").attr("src", t_url + "Photo_normal.jpg?v=" + Math.random());
$("#imgSmall").attr("src", t_url + "Photo_small.jpg?v=" + Math.random());
//alert("裁剪成功");
}
}
});
return false;
});


$('#file_upload').uploadify({
'uploader': '/Scripts/uploadify/uploadify.swf',
'script': '/Demo/ProcessRequest',
'cancelImg': '/Scripts/uploadify/cancel.png',
'folder': '/Uploads',
'auto': true,
'fileExt': '*.jpg;*.gif;*.png',
'fileDesc': 'Image Files',
'multi': false,
'sizeLimit': 2097152,
'buttonText': '上传头像',
'onComplete': function (event, ID, fileObj, response, data) {
var result = eval('(' + response + ')');
if (result.success == false) {
$.dialog.alert(result.msg);
$("#TestImage").attr("src", "/Content/images/vip/avatar.gif");
}
else {
isupload = true;
var msg = result.msg;
var fileName = msg;
if (msg.indexOf('#') > 0) {
fileName = msg.substring(0, msg.indexOf('#'));
}
var url = "/Uploads/Temp/" + fileName + "?v=" + Math.random();

$("#zoom01").html("<img id='TestImage' src='/Content/images/vip/avatar.gif' />");

$("#TestImage").attr("src", url);
$("#imageName").val(fileName);

if (msg.indexOf('#w') > 0) {
$("#TestImage").attr("width", "250");
}
else if (msg.indexOf('#h') > 0) {
$("#TestImage").attr("height", "250");
}
else {
$('#TestImage').removeAttr('width');
}
$("#imageName").val(fileName);
BeginJcrop();
}
}
});
});
</script>

Html代码:

<table border="0" style="width: 800px;" cellpadding="0" cellspacing="0">
<tr>
<td width="10%">
</td>
<td colspan="2">
<span>限上传格式:*.JPG、*.GIF、*.PNG、*.JPEG;限上传大小在2M以内</span><br />
<br />
<input type="file" name="file_upload" id="file_upload" />
</td>
<td>
&nbsp;
</td>
</tr>
<tr>
<td width="10%">
</td>
<td width="46%" valign="top">
<div id="zoom01">
<img id="TestImage" src="/Content/image/avatar.gif" /></div>
<p>
<button type="button" id="btnCut">
保存</button>
<button type="button">
取消</button>
</p>
</td>
<td width="34%" valign="top">
<div class="avatar-big">
<img id="imgBig" width="100" height="100" src="/Content/image/avatar_big.gif" /></div>
<p class="gray">
大尺寸头像(100x100)</p>
<div class="avatar-mid">
<img id="imgNormal" width="48" height="48" src="/Content/image/avatar_mid.gif" /></div>
<p class="gray">
中尺寸头像(48x48)</p>
<div class="avatar-small">
<img id="imgSmall" width="24" height="24" src="/Content/image/avatar_small.gif" /></div>
<p class="gray">
小尺寸头像(24x24)</p>
</td>
<td width="10%">
&nbsp;
</td>
</tr>
</table>
<form id="AvatarForm" action="">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="imageName" />
</form>

后台处理代码:

/// <summary>
/// 处理Uploadify上传(头像上传)
/// </summary>
/// <returns></returns>
public ActionResult ProcessRequest()
{
var file = Request.Files["Filedata"];
string uploadPath = Server.MapPath("~/Uploads/Temp/");
string file1 = file.ContentType;

if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}

string fileName = "Photo_original.jpg";
file.SaveAs(uploadPath + fileName);

Image ASrcImg = Image.FromFile(uploadPath + fileName);
int imgWidth = ASrcImg.Width;
int imgHeight = ASrcImg.Height;
ASrcImg.Dispose();

if (imgWidth < 100 || imgHeight < 100)
{
return Json(new AjaxResult { success = false, msg = "头像尺寸必须大于100*100" });
}
else if (imgWidth > 250 && imgWidth >= imgHeight)
{
return Json(new AjaxResult { success = true, msg = fileName + "#w" });
}
else if (imgHeight > 250 && imgHeight >= imgWidth)
{
return Json(new AjaxResult { success = true, msg = fileName + "#h" });
}
else
{
return Json(new AjaxResult { success = true, msg = fileName });
}

//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
//return Json(fileName);
}
else
{
return Json("0");
}
}

#region 图片处理

/// <summary>
/// 剪切图片
/// </summary>
/// <param name="xstr"></param>
/// <param name="ystr"></param>
/// <param name="wstr"></param>
/// <param name="hstr"></param>
/// <param name="imageName"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Cut(string xstr, string ystr, string wstr, string hstr, string imageName)
{
string sourceFile = Server.MapPath("~/Uploads/Temp/" + imageName);
string tempPath = Server.MapPath("~/Uploads/Space/Photo/");
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}

string savePath = Server.MapPath("~/Uploads/Temp/Photo_temp.jpg");
int x = 0;
int y = 0;
int w = 1;
int h = 1;
try
{
x = int.Parse(xstr);
y = int.Parse(ystr);
w = int.Parse(wstr);
h = int.Parse(hstr);
}
catch (Exception e) { throw e; }

Image sourceImg = Image.FromFile(sourceFile);

int imgWidth = sourceImg.Width;
int imgHeight = sourceImg.Height;
double rate = 1.0;

try
{
sourceImg.Save(tempPath + "Photo_original.jpg", ImageFormat.Jpeg);
sourceImg.Dispose();
}
catch (Exception e)
{
sourceImg.Dispose();
throw e;
}
finally { sourceImg.Dispose(); }

if (imgWidth > 250 && imgWidth > imgHeight)
{
rate = (double)imgWidth / 250;
}
if (imgHeight > 250 && imgHeight > imgWidth)
{
rate = (double)imgHeight / 250;
}
x = (int)(x * rate);
y = (int)(y * rate);
w = (int)(w * rate);
h = (int)(h * rate);

ImageCut ic = new ImageCut(x, y, w, h);
ic.KiCut(sourceFile, savePath);

Image img = Image.FromFile(savePath);
if (img.Width >= 100)
{
//100*100
DoConvert(savePath, tempPath + "Photo_big.jpg", 100, 100, 100);
}
else
{
//扩大到100*100
Mosaic(img, 100, "Photo");
}
if (img.Width >= 48)
{
//48*48
DoConvert(savePath, tempPath + "Photo_normal.jpg", 48, 48, 100);
}
else
{
//扩大到48*48
Mosaic(img, 48, "Photo");
}
if (img.Width >= 24)
{
//24*24
DoConvert(savePath, tempPath + "Photo_small.jpg", 24, 24, 100);
}
else
{
//扩大到24*24
Mosaic(img, 24, "Photo");
}
img.Dispose();

return Json(true);
}

/// <summary>
/// 图片转换(裁剪并缩放)
/// </summary>
/// <param name="ASrcFileName">源文件名称</param>
/// <param name="ADestFileName">目标文件名称</param>
/// <param name="AWidth">转换后的宽度(像素)</param>
/// <param name="AHeight">转换后的高度(像素)</param>
/// <param name="AQuality">保存质量(取值在1-100之间)</param>
public void DoConvert(string ASrcFileName, string ADestFileName, int AWidth, int AHeight, int AQuality)
{
Image ASrcImg = Image.FromFile(ASrcFileName);
if (ASrcImg.Width <= AWidth && ASrcImg.Height <= AHeight)
{//图片的高宽均小于目标高宽,直接保存
ASrcImg.Save(ADestFileName);
return;
}
double ADestRate = AWidth * 1.0 / AHeight;
double ASrcRate = ASrcImg.Width * 1.0 / ASrcImg.Height;
//裁剪后的宽度
double ACutWidth = ASrcRate > ADestRate ? (ASrcImg.Height * ADestRate) : ASrcImg.Width;
//裁剪后的高度
double ACutHeight = ASrcRate > ADestRate ? ASrcImg.Height : (ASrcImg.Width / ADestRate);
//待裁剪的矩形区域,根据原图片的中心进行裁剪
Rectangle AFromRect = new Rectangle(Convert.ToInt32((ASrcImg.Width - ACutWidth) / 2), Convert.ToInt32((ASrcImg.Height - ACutHeight) / 2), (int)ACutWidth, (int)ACutHeight);
//目标矩形区域
Rectangle AToRect = new Rectangle(0, 0, AWidth, AHeight);

Image ADestImg = new Bitmap(AWidth, AHeight);
Graphics ADestGraph = Graphics.FromImage(ADestImg);
ADestGraph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
ADestGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
ADestGraph.DrawImage(ASrcImg, AToRect, AFromRect, GraphicsUnit.Pixel);

//获取系统image/jpeg编码信息
ImageCodecInfo[] AInfos = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo AInfo = null;
foreach (ImageCodecInfo i in AInfos)
{
if (i.MimeType == "image/jpeg")
{
AInfo = i;
break;
}
}
//设置转换后图片质量参数
EncoderParameters AParams = new EncoderParameters(1);
AParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)AQuality);
//保存
try
{
ADestImg.Save(ADestFileName, AInfo, AParams);
ADestGraph.Dispose();
ADestImg.Dispose();
}
catch (Exception e)
{
ADestGraph.Dispose();
ADestImg.Dispose();
ASrcImg.Dispose();
throw e;
}
finally
{
ADestGraph.Dispose();
ADestImg.Dispose();
ASrcImg.Dispose();
}
}

/// <summary>
/// 图片扩大
/// </summary>
/// <param name="img">原图片</param>
/// <param name="scale">扩大尺寸</param>
/// <param name="strUserID"></param>
void Mosaic(Image img, int scale, string strUserID)
{
Bitmap original = new Bitmap(img);
Bitmap result = new Bitmap(scale, scale);
using (Graphics g = Graphics.FromImage(result))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
g.DrawImage(original, 0, 0, result.Width, result.Height);
string strName = "_big.jpg";
if (scale == 48)
strName = "_normal.jpg";
if (scale == 24)
strName = "_small.jpg";
string tempPath = Server.MapPath("~/Uploads/Space/" + strUserID + "/Photo/");
result.Save(tempPath + strUserID + strName, ImageFormat.Jpeg);
}
original.Dispose();
}


#endregion

public class ImageCut
{
/// <summary>
/// 剪裁 -- 用GDI+
/// </summary>
/// <param name="b">原始Bitmap</param>
/// <param name="StartX">开始坐标X</param>
/// <param name="StartY">开始坐标Y</param>
/// <param name="iWidth">宽度</param>
/// <param name="iHeight">高度</param>
/// <returns>剪裁后的Bitmap</returns>
public Bitmap KiCut(Bitmap b)
{
if (b == null)
{
return null;
}

int w = b.Width;
int h = b.Height;

if (X >= w || Y >= h)
{
return null;
}

if (X + Width > w)
{
Width = w - X;
}

if (Y + Height > h)
{
Height = h - Y;
}

try
{ }
catch
{
return null;
}
Bitmap bmpOut = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);

Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, Width, Height), new Rectangle(X, Y, Width, Height), GraphicsUnit.Pixel);
g.Dispose();
b.Dispose();
return bmpOut;

}

public int X = 0;
public int Y = 0;
public int Width = 120;
public int Height = 120;
public ImageCut(int x, int y, int width, int heigth)
{
X = x;
Y = y;
Width = width;
Height = heigth;
}


public void KiCut(string sourceFile, string savePath)
{
Image imgPhoto = Image.FromFile(sourceFile);
Bitmap bmPhoto = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, Width, Height), new Rectangle(X, Y, Width, Height), GraphicsUnit.Pixel);

MemoryStream ms2 = new MemoryStream();
bmPhoto.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);

imgPhoto.Dispose();
gbmPhoto.Dispose();
bmPhoto.Dispose();

FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter(fs);
w.Write(ms2.ToArray());
fs.Close();
ms2.Close();
}
}

  上面这些就是代码了,从学习、收集资料,到实现,大概花了两天时间,感觉效果还是不错的,如果有更好的插件或者实现方式,请各位指教。

posted on 2011-12-15 16:37  shine0210  阅读(645)  评论(2)    收藏  举报

导航