网页上传图片 判断类型 检测大小 剪切图片 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 ...
随机推荐
- 按要求编写Java应用程序。 (1)创建一个叫做机动车的类: 属性:车牌号(String),车速(int),载重量(double) 功能:加速(车速自增)、减速(车速自减)、修改车牌号,查询车的载重量。 编写两个构造方法:一个没有形参,在方法中将车牌号设置“XX1234”,速 度设置为100,载重量设置为100;另一个能为对象的所有属性赋值; (2)创建主类: 在主类中创建两个机动车对象。 创建第
package com.hanqi.test; public class jidongche { private String chepaihao;//车牌号 private int speed;// ...
- easyui datagrid 键盘上下控制选中行
扩展datagrid的一个方法keyCtr $.extend($.fn.datagrid.methods, { keyCtr : function (jq) { return jq.each(fun ...
- 今天说一下Top ~
Top这个关键字,大家都不陌生~尤其是很多时候打开SSMS的时候右键表名,选择前1000行的时候,就可以见到编译出来的语句 Select top 1000 XXX from XXX 好~我们先看看To ...
- 关于TreeView的选中事件
在使用TreeView的选中事件时,发现,SelectAfter在第一次选中时触发,你再次点击时这个事件并不能引发它.所以找了找,发现有另两种解决办法. 最好的就是使用:NodeMouseClick, ...
- kernel启动console_init之前console不可用时发生crash的调试方法
http://code.google.com/p/innosoc/wiki/KernelBootCrashDebug 注: 如在i386_start_kernel中加入:early_printk(&q ...
- height:100%不起作用(无效),div全屏
当父容器是body时,height:100%不起作用(无效),解决办法:在css代码段中添加 html, body{ margin:0; height:100%; } 实现div全屏的时候需要上面那段 ...
- 磁盘配额-----quota
为什么要使用磁盘配额:为了限制普通用户使用普通磁盘的空间与创建文件的个数等. 不至于个别人的浪费影响所有人的使用. 需要安装quota的软件包. mount -o usrquota,grpquota ...
- php 连续留存与留存人数计算
for($i = 0;$i <= $interval;$i++) { $res = $model->turnround($today,$tomorrow,$flag); $temp = a ...
- monkeyrunner之安卓开发环境搭建(一)
在学习monkeyrunner之前,让我们先搭建好eclipse安卓开发环境. 对于程序开发人员而言,eclipse并不陌生,它提供了一个非常广阔的平台来开发程序.同样也可以用它来开发android程 ...
- plain framework 1 参考手册 入门指引之简介
简介 简介 能做什么? LINUX WINDOWS 简介 简约框架(plain framework)是一款基于C/C++开发的,跨平台(windows/linux)应用的基础框架,开发者可以利用此框架 ...