网页上传图片 判断类型 检测大小 剪切图片 ASP.NET版本
本文转载自: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 != )
{
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版本的更多相关文章
- PHP判断上传图片的类型
PHP判断上传图片的类型用getimagesize来判断上传图片的类型比$_FILES函数的type更可靠 同一个文件,使用不同的浏览器php返回的type类型是不一样的,由浏览器提供type类型的话 ...
- 判断网页打开浏览器类型,PC 手机端,微信浏览器,,,
//判断网页打开浏览器类型,PC 手机端,微信浏览器,,, <script type="text/javascript"> var browser = { versio ...
- 我给女朋友讲编程CSS系列(3) CSS如何设置字体的类型、大小、颜色,如何使用火狐浏览器的Firebug插件查看网页的字体
一.CSS如何设置字体的类型.大小.颜色 设计网页时,一般设置body的字体,让其他标签继承body的字体,这样设置特别方便,但是标题标签h1到h6和表单标签(input类型)是没有继承body的字体 ...
- 谈谈JavaScript类型检测
javascript内置的类型检测机制并非完全可靠.比如typeof操作符,并不能准确的判断数据是哪个类型,比如:数组和对象就不能通过typeof来区分. typeof [] ==="o ...
- 利用Struts拦截器限制上传图片的格式和大小
在这之前 Struts的一个核心功能就是大量的拦截器,既然是框架,那么自然也就贴心地为我们准备好了各种常用的功能,比如这里即将讨论的如何限制上传图片的格式和大小.那么既然是使用Struts已经写好的拦 ...
- 判断是否为gif/png图片的正确姿势
判断是否为gif/png图片的正确姿势 1.在能取到图片后缀的前提下 1 2 3 4 5 6 7 8 9 //假设这是一个网络获取的URL NSString *path = @"http:/ ...
- js判断类型方法
在JavaScript中,有5种基本数据类型和1种复杂数据类型,基本数据类型有:Undefined, Null,Boolean, Number和String:复杂数据类型是Object,Object中 ...
- STUN: NAT 类型检测方法
STUN(Simple Transversal of UDP through NATs)[21]是RFC3489 规定的一种NAT 穿透方式,它采用辅助的方法探测NAT 的IP 和端口. STUN 的 ...
- [改善Java代码] 谨慎包装类型的大小比较
建议27:谨慎包装类型的大小比较 基本数据类型比较大小木有问题,不过其对应的包装类型大小比较就需要注意了.看如下代码: public class Client { public static void ...
随机推荐
- pom.xml 样例
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven ...
- mysqldump 逻辑备份的正确姿势
在上一篇文章 MySQL 命令行工具之 mysqldump 深入研究 中,我们搞定了mysqldump的参数和基本原理.那么我们该怎么样最好的使用它的?它有哪些坑呢? 1. 利用mysqldump进行 ...
- 照片大管家iOS-实现本地相册、视频、安全保护、社交分享一站式功能,源码开放
<照片大管家> APP功能: 1.本地照片批量导入与编辑 2.本地视频存储与播放 3.手势密码.数字密码.TouchID安全保护 4.QQ.微信.微博.空间社交分享 5.其他细节功能. 运 ...
- Windows 安装ELK
在Windows服务器上安装ELK logstash在windows平台下不能监控磁盘文件,用nxlog代替,监控文件并把内容发送到logstash 部署环境 Os :Windows 7 logsta ...
- ThinkPHP3.1.3源码分析---php文件压缩zlib.output_compression 和 ob_gzhandler
问题来源:\ThinkPHP3.1.3_full\ThinkPHP\Lib\Core\App.class.php 中 init()方法 if(C('OUTPUT_ENCODE')){ ...
- find 命令
1.当前目录下查找"test.cpp"文件 find ./ -name test.cpp 2.当前查找含有"abcdef"字符串的文件 find ./ | xa ...
- [转]android 获取视频帧
本文转自:http://blog.csdn.net/heart_Moving/article/details/17414067 今天做Android视频文件解码,需求:从一个视频文件获取到一帧一帧的图 ...
- json与jsonp小结
json 1. json 的值可以是下面这些类型: ① 数字(整数或浮点数),比如123,1.23 ② 字符串(在双引号中) ③ 逻辑值(true 或 false) ④ 数组(在方括号中) ⑤ 对象( ...
- Web学习之html
超文本标记语言(英语:HyperText Markup Language,简称:HTML)是一种用于创建网页的标准标记语言.HTML是一种基础技术,常与CSS.JavaScript一起被众多网站用于设 ...
- csu 1812: 三角形和矩形 凸包
传送门:csu 1812: 三角形和矩形 思路:首先,求出三角形的在矩形区域的顶点,矩形在三角形区域的顶点.然后求出所有的交点.这些点构成一个凸包,求凸包面积就OK了. /************** ...