本文转载自:http://www.youarebug.com/forum.php?mod=viewthread&tid=56&extra=page%3D1

我们在网页上传图片的时候,特别是上传图像等操作,需要限制用户上传图片的类型、大小、有时候还需要对图片进行剪切。这样的需求在我们工作中经常遇到。今天就来说说在web开发中,如何对上传的图片判断文件的类型、检查文件的大小、对图片进行可视化裁剪等操作。很少写帖子,有不足之处,请不吝赐教。先上图看看效果:

<ignore_js_op style="-ms-word-wrap: break-word;">

主要采用的技术: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文件夹中。
     如果上面没有文件夹请自己新建。
现在的文件结构如下

<ignore_js_op style="-ms-word-wrap: break-word;"> 

3、在Script/js下创建ImgUpload.js文件,内容为:
$(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 != )
{
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(, );
//从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(, , , );
gr.DrawImage(image, rectDestination, , , 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

网页上传图片 判断类型 检测大小 剪切图片 ASP.NET版本的更多相关文章

  1. PHP判断上传图片的类型

    PHP判断上传图片的类型用getimagesize来判断上传图片的类型比$_FILES函数的type更可靠 同一个文件,使用不同的浏览器php返回的type类型是不一样的,由浏览器提供type类型的话 ...

  2. 判断网页打开浏览器类型,PC 手机端,微信浏览器,,,

    //判断网页打开浏览器类型,PC 手机端,微信浏览器,,, <script type="text/javascript"> var browser = { versio ...

  3. 我给女朋友讲编程CSS系列(3) CSS如何设置字体的类型、大小、颜色,如何使用火狐浏览器的Firebug插件查看网页的字体

    一.CSS如何设置字体的类型.大小.颜色 设计网页时,一般设置body的字体,让其他标签继承body的字体,这样设置特别方便,但是标题标签h1到h6和表单标签(input类型)是没有继承body的字体 ...

  4. 谈谈JavaScript类型检测

      javascript内置的类型检测机制并非完全可靠.比如typeof操作符,并不能准确的判断数据是哪个类型,比如:数组和对象就不能通过typeof来区分. typeof [] ==="o ...

  5. 利用Struts拦截器限制上传图片的格式和大小

    在这之前 Struts的一个核心功能就是大量的拦截器,既然是框架,那么自然也就贴心地为我们准备好了各种常用的功能,比如这里即将讨论的如何限制上传图片的格式和大小.那么既然是使用Struts已经写好的拦 ...

  6. 判断是否为gif/png图片的正确姿势

    判断是否为gif/png图片的正确姿势 1.在能取到图片后缀的前提下 1 2 3 4 5 6 7 8 9 //假设这是一个网络获取的URL NSString *path = @"http:/ ...

  7. js判断类型方法

    在JavaScript中,有5种基本数据类型和1种复杂数据类型,基本数据类型有:Undefined, Null,Boolean, Number和String:复杂数据类型是Object,Object中 ...

  8. STUN: NAT 类型检测方法

    STUN(Simple Transversal of UDP through NATs)[21]是RFC3489 规定的一种NAT 穿透方式,它采用辅助的方法探测NAT 的IP 和端口. STUN 的 ...

  9. [改善Java代码] 谨慎包装类型的大小比较

    建议27:谨慎包装类型的大小比较 基本数据类型比较大小木有问题,不过其对应的包装类型大小比较就需要注意了.看如下代码: public class Client { public static void ...

随机推荐

  1. Mysql数据库的通用安装方法

    安装方式简介 Mysql数据库也时不时的用过一段时间,具体使用的功能都比较浅显,没有具体深入学习.最近一段在公司部署iNeedle系统时经常避免不了要安装apache和Mysql数据库.一般Mysql ...

  2. x01.os.16: 添加功能

    准备工作  1.确保是 win xp,如是 win 8,运行 nasm 需按提示同意安装组件.  2.确保 src 和 z_tools 在同一目录下,nasm 已包含在 z_tools 文件夹中.  ...

  3. android Eclipse执行项目提示错误: unable to execute dex: GC orerhead limit exceeded

    Eclipse执行项目提示错误: unable to execute dex: GC orerhead limit exceeded 解决方法: 找到Eclipse安装目录的文件,\eclipse\e ...

  4. Kali Linux 秘籍/Web渗透秘籍/无线渗透入门

    Kali Linux 秘籍 原书:Kali Linux Cookbook 译者:飞龙 在线阅读 PDF格式 EPUB格式 MOBI格式 Github Git@OSC 目录: 第一章 安装和启动Kali ...

  5. kernel启动console_init之前console不可用时发生crash的调试方法

    http://code.google.com/p/innosoc/wiki/KernelBootCrashDebug 注: 如在i386_start_kernel中加入:early_printk(&q ...

  6. python 的异常及其处理

    Python 异常处理 python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误.你可以使用该功能来调试python程序. 异常处理: 本站Python教程会具体介绍. 断言 ...

  7. 使用HTTP方式远程连接PowerShell

    借助Windows PowerShell,我们可以像管理Linux一样使用命令行来远程管理Windows服务器.但是默认情况下,我们只能在域环境中使用PowerShell Remoting.如果是通过 ...

  8. [转]C# 连接 Oracle 的几种方式

    本文转自:http://www.cnblogs.com/storys/archive/2013/03/06/2945914.html 一:通过System.Data.OracleClient(需要安装 ...

  9. C++11 之 override

    1  公有继承 派生类公有继承自 (public inheritance) 基类,继承包含两部分:一是函数的 "接口" (interface),二是函数的 "实现&quo ...

  10. codevs1004四子连棋[BFS 哈希]

    1004 四子连棋   时间限制: 1 s   空间限制: 128000 KB   题目等级 : 黄金 Gold   题目描述 Description 在一个4*4的棋盘上摆放了14颗棋子,其中有7颗 ...