本文转载自:http://www.youarebug.com/forum.php?mod=viewthread&tid=56&extra=page%3D1
我们在网页上传图片的时候,特别是上传图像等操作,需要限制用户上传图片的类型、大小、有时候还需要对图片进行剪切。这样的需求在我们工作中经常遇到。今天就来说说在web开发中,如何对上传的图片判断文件的类型、检查文件的大小、对图片进行可视化裁剪等操作。很少写帖子,有不足之处,请不吝赐教。先上图看看效果:
主要采用的技术:1、jquery.uploadify 用于图片上传
检查图片大小官网:http://www.uploadify.com/
2、imgAreaSelect
用于选择要剪切的图片区域 官网:http://odyniec.net/projects/imgareaselect/
下载上面两个文件包待用。
步骤:
1、创建ASP.net mvc3工程
工程名为ImgUpload.
2、拷贝jquery.imgareaselect-0.9.10文件夹下面的jquery.imgareaselect.min.js文件到Scripts下面的js文件夹中。
拷贝jquery.imgareaselect-0.9.10文件夹下面的css文件夹到Content下面。
拷贝uploadify文件夹下面的jquery.uploadify.min.js文件到Scripts下面的js文件夹中。
拷贝uploadify文件夹下面的uploadify.swf文件到Content下面的swf文件夹中。
如果上面没有文件夹请自己新建。
现在的文件结构如下
$(function () { $(‘#fileToUpload‘).uploadify({ ‘progressData‘: ‘speed‘, ‘multi‘: false, ‘method‘: ‘post‘, ‘queueID‘: ‘some_file_queue‘, ‘fileSizeLimit‘: ‘1000k‘, ‘fileTypeDesc‘: ‘Image Files‘, ‘fileTypeExts‘: ‘*.gif; *.jpg; *.png‘, ‘swf‘: ‘/Content/swf/uploadify.swf‘, ‘uploader‘: ‘/User/UploadImg‘, ‘onUploadStart‘: function (file) { $(‘#fileToUpload‘).uploadify(‘disable‘, true) }, ‘onUploadComplete‘: function (file) { $(‘#fileToUpload‘).uploadify(‘disable‘, false) }, ‘onUploadSuccess‘: function (file, data, response) { $(‘#fileToUpload‘).uploadify(‘disable‘, false) $("#PreviewImg").attr("src", "/Content/TempImg/" + data); $("#PreviewImg").attr("data-value", data); } // Put your options here }); $(‘#PreviewImg‘).imgAreaSelect({ handles: true, onSelectEnd: preview }); $("#savebtn").click(function () { $.ajax({ url: "/User/SaveHeaderImg?fileName=" + $("#preview_img").attr("src"), dataType: "text", success: function (json) { $("#tiebaSaveOkMsg").attr("style", "font-size: 110%; font-weight: bold; padding-left: 0.1em;display: block;"); $("#savebtn_swap").attr("style", "display:none"); } }); }); }); function preview(img, selection) { if (!selection.width || !selection.height) return; var previewImg = $("#PreviewImg").attr("src"); if (‘/Content/Header/defaut.png‘ == previewImg) return; $.ajax({ url: "/User/CutoutImg?fileName=" + previewImg + "&top=" + selection.y1 + "&left=" + selection.x1 + "&width=" + selection.width + "&height=" + selection.height, dataType: "text", success: function (json) { $("#preview_img").attr("src", "/Content/TempImg/" + json); $("#savebtn_swap").attr("style", "display:block;text-align:center; "); $("#tiebaSaveOkMsg").attr("style", "display:none"); } }); }
4、创建Home控制器。添加ImgUpload方法以及视图。
ImgUpload视图的代码如下:
@{ ViewBag.Title = "HeaderImgPage"; Layout = null; } <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/uploadify.css")"> <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/imgareaselect-animated.css")"> <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/imgareaselect-default.css")"> <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/imgareaselect-deprecated.css")"> <script src="@Url.Content("~/Scripts/jquery-1.5.1.js ")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/js/ImgUpload.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/js/jquery.uploadify.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/js/jquery.imgareaselect.min.js")" type="text/javascript"></script> <style type="text/css"> body { background:#fff; } </style> <div class="container-box"> <p style="font-size: 110%; font-weight: bold; padding-left: 0.1em;"> 1、择一张图片 </p> <div > <div style=" float:left; height:50px"> <input type="file" id="fileToUpload" name="fileToUpload" /> </div> <div id="some_file_queue" style=" float:left;height:50px; width:300px; margin-left:30px; "></div> </div> <div style="float: left; clear:both;"> <p style="font-size: 110%; font-weight: bold; padding-left: 0.1em;"> 2、点击鼠标拖动相框截取图像 </p> <div class="frame" style="margin: 0 0.3em; width: 300px; height: 300px;"> <img id="PreviewImg" src="/Content/defaut.png" style="width: 300px; height: 300px;"> </div> </div> <div style="float: left;"> <p style="font-size: 110%; font-weight: bold; padding-left: 0.1em;"> 3、预览截取的图像,点击保存。 </p> <div style="text-align:center"> <div class="frame" style="margin: 0 auto; width: 100px; height: 100px;"> <img id="preview_img" src="/Content/defaut.png" style="width: 100px; height: 100px;"> </div> </div> <div id="savebtn_swap" style="text-align:center; display:none"> <div style="margin: 20 auto 0 auto; width:70px;"> <input type="submit" id="savebtn" class="setting-submit-btn setting-submit-ml100" value="保存"> </div> </div> <div class="save-ok" style="font-size: 110%;text-align:center; font-weight: bold; padding-left: 0.1em;display: none;" id="tiebaSaveOkMsg" > <div style="margin: 20 auto 0 auto; width:90px;"> <p>保存成功</p> </div> </div> </div> </div>
5、在Home控制器中添加UploadImg,CutoutImg,SaveHeaderImg方法,添加后代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.IO; using System.Drawing; namespace ImgUpload.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult ImgUpload() { return View(); } /// <summary> /// 上传图片接口 上传头像使用 /// </summary> /// <returns></returns> [HttpPost] public String UploadImg() { HttpPostedFileBase postedFile_pic = Request.Files["Filedata"];//获取上传信息对象 if (postedFile_pic != null && postedFile_pic.ContentLength != 0) { String PicFilePath = postedFile_pic.FileName;//获取上传的文件路径 String PicName = Path.GetFileNameWithoutExtension(postedFile_pic.FileName);//获取文件名 String SavePath = Server.MapPath("/Content/TempImg/"); String PicExtension = PicFilePath.Substring(PicFilePath.LastIndexOf(‘.‘));//获取拓展名 //构造随机名称 String Photo = PicName + "_" + DateTime.Now.Ticks + PicExtension; postedFile_pic.SaveAs(SavePath + Photo); //规格化 System.Drawing.Image image = System.Drawing.Image.FromFile(SavePath + Photo); //接着创建一个System.Drawing.Bitmap对象,并设置你希望的缩略图的宽度和高度。 int srcWidth = image.Width; int srcHeight = image.Height; Bitmap bmp = new Bitmap(300, 300); //从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。 System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp); //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //下面这个也设成高质量 gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //下面这个设成High gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //把原始图像绘制成上面所设置宽高的缩小图 System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, 300, 300); gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel); String NewPhoto = "__" + PicName + "_" + DateTime.Now.Ticks + PicExtension; bmp.Save(SavePath + NewPhoto); bmp.Dispose(); image.Dispose(); FileInfo fi = new FileInfo(SavePath + Photo); fi.Delete(); return NewPhoto; } return "Invalid file type"; } /// <summary> /// 裁剪图片 /// </summary> /// <param name="fileName"></param> /// <param name="top"></param> /// <param name="left"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public String CutoutImg(String fileName, int top, int left, int width, int height) { String PicExtension = fileName.Substring(fileName.LastIndexOf(‘.‘));//获取拓展名 String Photo = "__" + DateTime.Now.Ticks + PicExtension; String RootPath = Server.MapPath("/"); String HeaderImgPath = Server.MapPath("/Content/TempImg/"); Bitmap bmp = new Bitmap(RootPath + fileName); Rectangle rect = new Rectangle(left, top, width, height); Bitmap tempBitmap = bmp.Clone(rect, bmp.PixelFormat); tempBitmap.Save(HeaderImgPath + Photo); bmp.Dispose(); tempBitmap.Dispose(); return Photo; } public String SaveHeaderImg(String fileName) { String RootPath = Server.MapPath("/"); String PicExtension = fileName.Substring(fileName.LastIndexOf(‘.‘)); String NewName = "__" + DateTime.Now.Ticks + PicExtension; String HeaderImgPath = Server.MapPath("/Content/Header/"); FileInfo fi = new FileInfo(RootPath + fileName); fi.MoveTo(HeaderImgPath + NewName); return ""; } } }
6、运行,在浏览器中输入http://localhost:6133/Home/ImgUpload即可。
保存后的截图保存在Content/Header文件夹下面。
7、完整源码下载
http://www.youarebug.com/forum.php?mod=viewthread&tid=56&extra=page%3D1