webuploader插件单张上传或批量上传效果如下
HTML文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="WebUploader.Demo" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link href="css/smart-green.css" rel="stylesheet" /> <link rel="stylesheet" type="text/css" href="webuploader/webuploader.css" /> //webuplaoder样式文件 <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> //先引用jquery插件 <script type="text/javascript" src="webuploader/webuploader.min.js"></script> //webuploader插件 <script type="text/javascript" charset="utf-8" src="js/uploader.js"></script> //JS动态图片配置操作信息 <style type="text/css"> .fl { //相册图片ul li样式向左浮动,JS文件uploader.js里动态添加 float: left; width: 350px; list-style-type: none; } .clear { //清除浮动 clear: both; } .tab ul li { //单张上传格式排版样式 line-height: 30px; list-style-type: none; } .lef { float: left; width: 90px; } .rig { float: left; width: 870px; } </style> </head> <body> <form id="form1"> <div class="smart-green tab"> <h1>webuploader图片单张,多张批量上传,可设置生成缩略图 <span>运用webuploader无刷新上传图片</span> </h1> <ul style="height: 320px;"> <li class="lef"><span>单张上传:</span></li> <li class="rig"> <input type="text" style="float: left; height: 30px; width: 450px;" readonly="readonly" name="txtImgUrl" class="upload-path" /> //upload-path表示图片上传后返回的文件名带目录接受类 <div style="float: left; margin-left: 8px;" class="upload-box upload-img"></div> //引用upload-img动态JS添加一个按钮 <div style="clear: both;"></div> <img id="imageurl" class="upload-imgurl" width="300" /> //upload-imgurl表示上传后返回接受类 </li> <li class="clear"></li> </ul> <ul> <li class="lef"><span>批量上传</span></li> <li class="rig"> <div style="float: left; " class="upload-box upload-album"></div> //引用upload-album动态JS添加一个按钮 <div style="float: left; margin-left: 8px;"><input id="chkThumb" name="chkThumb" type="checkbox" value="1" /><label for="chkThumb">是否生成缩略图</label></div> <div class="clear"></div> <div class="photo-list"> //批量上传后动态返回接收的photo-list类,内容写在<ul>内 <ul> <%--<li> <input type="hidden" name="hid_photo_name" value="" /> //返回的隐藏input名为hid_photo_name,后台获取将是一个数组
//单个值/Upload/20160625215133272.jpg|,带缩略图/Upload/20160625223245312.jpg|/Upload/thumb_20160625223245312.jpg <input type="hidden" name="hid_photo_remark" value="" /> //可以给图片添加描述信息 <div class="img-box" onclick="setFocusImg(this);"> <img src="" bigsrc="" /> <span class="remark"><i>暂无描述...</i></span> </div> <a href="javascript:;" onclick="setRemark(this);">描述</a> //添加图片描述 <a href="javascript:;" onclick="delImg(this);">删除</a> //删除图片按钮 </li>--%> </ul> </div> </li> <li class="clear"></li> </ul> <%--<label> <span> </span> <input type="button" class="button" value="Save" /> </label>--%> </div> </form> </body> <script type="text/javascript"> $(function () { //初始化上传控件 $(".upload-img").InitUploader({ sendurl: "/ajax.ashx", }); $(".upload-album").InitUploader({ btntext: "批量上传", multiple: true, water: false, thumbnail: false, sendurl: "/ajax.ashx", }); }); </script> </html>
以下是封装好的uploader.js文件
$(function () { //初始化绑定默认的属性 $.upLoadDefaults = $.upLoadDefaults || {}; $.upLoadDefaults.property = { multiple: false, //是否多文件 water: false, //是否加水印 thumbnail: false, //是否生成缩略图 sendurl: null, //发送地址 filetypes: "jpg,jpge,png,gif", //文件类型 filesize: "2048", //文件大小 btntext: "浏览...", //上传按钮的文字 swf: "/webuploader/uploader.swf" //SWF上传控件相对地址,上传SWF需要用到的文件 }; //初始化上传控件 $.fn.InitUploader = function (b) { var fun = function (parentObj) { var p = $.extend({}, $.upLoadDefaults.property, b || {}); var btnObj = $('<div class="upload-btn">' + p.btntext + '</div>').appendTo(parentObj); //初始化属性 p.sendurl += "?action=UpLoadFile"; if (p.water) { p.sendurl += "&IsWater=1"; } if (p.thumbnail) { p.sendurl += "&IsThumbnail=1"; } //if (!p.multiple) { // p.sendurl += "&DelFilePath=" + parentObj.siblings(".upload-path").val(); //} //初始化WebUploader var uploader = WebUploader.create({ auto: true, //自动上传 swf: p.swf, //SWF路径 server: p.sendurl, //上传地址 pick: { id: btnObj, multiple: p.multiple }, accept: { /*title: 'Images',*/ extensions: p.filetypes /*mimeTypes: 'image/*'*/ }, formData: { 'DelFilePath': '', //定义参数 url: '算定义参数' }, fileVal: 'Filedata', //上传域的名称 fileSingleSizeLimit: p.filesize * 1024 //文件大小 }); //当validate不通过时,会以派送错误事件的形式通知 uploader.on('error', function (type) { switch (type) { case 'Q_EXCEED_NUM_LIMIT': alert("错误:上传文件数量过多!"); break; case 'Q_EXCEED_SIZE_LIMIT': alert("错误:文件总大小超出限制!"); break; case 'F_EXCEED_SIZE': alert("错误:文件大小超出限制!"); break; case 'Q_TYPE_DENIED': alert("错误:禁止上传该类型文件!"); break; case 'F_DUPLICATE': alert("错误:请勿重复上传该文件!"); break; default: alert('错误代码:' + type); break; } }); //当有文件添加进来的时候 uploader.on('fileQueued', function (file) { //如果是单文件上传,把旧的文件地址传过去 if (!p.multiple) { uploader.options.formData.DelFilePath = parentObj.siblings(".upload-path").val(); } //是否生成缩略图 if (!p.thumbnail) { uploader.options.formData.thumbnail = $('#chkThumb').is(':checked'); } //防止重复创建 if (parentObj.children(".upload-progress").length == 0) { //创建进度条 var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj); var progressText = $('<span class="txt">正在上传,请稍候...</span>').appendTo(fileProgressObj); var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj); var progressCancel = $('<a class="close" title="取消上传">关闭</a>').appendTo(fileProgressObj); //绑定点击事件 progressCancel.click(function () { uploader.cancelFile(file); fileProgressObj.remove(); }); } }); //文件上传过程中创建进度条实时显示 uploader.on('uploadProgress', function (file, percentage) { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html(file.name); progressObj.find(".bar b").width(percentage * 100 + "%"); }); //当文件上传出错时触发 uploader.on('uploadError', function (file, reason) { uploader.removeFile(file); //从队列中移除 alert(file.name + "上传失败,错误代码:" + reason); }); //当文件上传成功时触发 uploader.on('uploadSuccess', function (file, data) { if (data.status == '0') { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html(data.msg); } if (data.status == '1') { //如果是单文件上传,则赋值相应的表单 if (!p.multiple) { parentObj.siblings(".upload-name").val(data.name); parentObj.siblings(".upload-size").val(data.size); parentObj.siblings(".upload-imgurl").attr("src", data.path); parentObj.siblings(".upload-path").val(data.path); } else { addImage(parentObj, data.path, data.thumb); } var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html("上传成功:" + file.name); } uploader.removeFile(file); //从队列中移除 }); //不管成功或者失败,文件上传完成时触发 uploader.on('uploadComplete', function (file) { var progressObj = parentObj.children(".upload-progress"); progressObj.children(".txt").html("上传完成"); //如果队列为空,则移除进度条 if (uploader.getStats().queueNum == 0) { progressObj.remove(); } }); }; return $(this).each(function () { fun($(this)); }); } }); /*图片相册处理事件 =====================================================*/ //添加图片相册 function addImage(targetObj, originalSrc, thumbSrc) { //插入到相册UL里面 var newLi = $('<li class="fl">' + '<img id="imagelist" class="imgage-list" width="300" src="' + originalSrc + '"/>' + '<input type="hidden" name="hid_photo_name" value="' + originalSrc + '|' + thumbSrc + '" />' + '<input type="hidden" name="hid_photo_remark" value="" />' //+ '<div class="img-box" onclick="setFocusImg(this);">' //+ '<img src="' + thumbSrc + '" bigsrc="' + originalSrc + '" />' //+ '<span class="remark"><i>暂无描述...</i></span>' //+ '</div>' //+ '<a href="javascript:;" onclick="setRemark(this);">描述</a>' + '<a href="javascript:;" onclick="delImg(this);">删除</a>' + '</li>'); newLi.appendTo(targetObj.siblings(".photo-list").children("ul")); //默认第一个为相册封面 var focusPhotoObj = targetObj.siblings(".focus-photo"); if (focusPhotoObj.val() == "") { focusPhotoObj.val(thumbSrc); newLi.children(".img-box").addClass("selected"); } } //设置相册封面 function setFocusImg(obj) { var focusPhotoObj = $(obj).parents(".photo-list").siblings(".focus-photo"); focusPhotoObj.val($(obj).children("img").eq(0).attr("src")); $(obj).parent().siblings().children(".img-box").removeClass("selected"); $(obj).addClass("selected"); } //设置图片描述 function setRemark(obj) { var parentObj = $(obj); //父对象 var hidRemarkObj = parentObj.prevAll("input[name='hid_photo_remark']").eq(0); //取得隐藏值 var d = parent.dialog({ title: "图片描述", content: '<textarea id="ImageRemark" style="margin:10px 0;font-size:12px;padding:3px;color:#000;border:1px #d2d2d2 solid;vertical-align:middle;width:300px;height:50px;">' + hidRemarkObj.val() + '</textarea>', button: [{ value: '批量描述', callback: function () { var remarkObj = $('#ImageRemark', parent.document); if (remarkObj.val() == "") { parent.dialog({ title: '提示', content: '亲,总该写点什么吧?', okValue: '确定', ok: function () { }, onclose: function(){ remarkObj.focus(); } }).showModal(); return false; } parentObj.parent().parent().find("li input[name='hid_photo_remark']").val(remarkObj.val()); parentObj.parent().parent().find("li .img-box .remark i").html(remarkObj.val()); } }, { value: '单张描述', callback: function () { var remarkObj = $('#ImageRemark', parent.document); if (remarkObj.val() == "") { parent.dialog({ title: '提示', content: '亲,总该写点什么吧?', okValue: '确定', ok: function () { }, onclose: function () { remarkObj.focus(); } }).showModal(); return false; } hidRemarkObj.val(remarkObj.val()); parentObj.siblings(".img-box").children(".remark").children("i").html(remarkObj.val()); }, autofocus: true }] }).showModal(); } //删除图片LI节点 function delImg(obj) { var parentObj = $(obj).parent().parent(); var focusPhotoObj = parentObj.parent().siblings(".focus-photo"); var smallImg = $(obj).siblings(".img-box").children("img").attr("src"); $(obj).parent().remove(); //删除的LI节点 //检查是否为封面 if (focusPhotoObj.val() == smallImg) { focusPhotoObj.val(""); var firtImgBox = parentObj.find("li .img-box").eq(0); //取第一张做为封面 firtImgBox.addClass("selected"); focusPhotoObj.val(firtImgBox.children("img").attr("src")); //重新给封面的隐藏域赋值 } }
ajax.ashx文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; namespace Project_Demo.Common { /// <summary> /// _Ajax 的摘要说明 /// </summary> public class _Ajax : IHttpHandler { string result = string.Empty; public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string type = context.Request.QueryString["action"]; switch (type) { case "UpLoadFile": UploadImage(context); break; default: //Uploader(context); break; } context.Response.Write(result); context.Response.End(); } private void UploadImage(HttpContext context) { string isthumb = context.Request.Form["thumbnail"]; bool thumb = isthumb == "true" ? true : false; //上传图片 HttpPostedFile postedFile = context.Request.Files[0]; var path = "/Upload/"; //上传保存的路径 int size = 2; //文件大小限制,单位mb ImageHelper up = new ImageHelper(); //var upImage = up.UploadImage(postedFile, path, size, false); //生成缩略图 var upImage = up.UploadImage(postedFile, path, size, thumb, 200); //生成水印 //var upImage = up.UploadImage(postedFile, path, size, WatermarkType.Text, "水印文字", WatermarkPosition.Center, false); //生成水印+缩略图 //var upImage = up.UploadImage(postedFile, path, size, WatermarkType.Text, "水印文字", WatermarkPosition.Center, true, 200); result = JsonConvert.SerializeObject(upImage); } public bool IsReusable { get { return false; } } } }
ImageHelper.cs类
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Web; /// <summary> /// 图片通用上传类 /// </summary> public class ImageHelper { protected UploadImageInfo upImage = new UploadImageInfo(); /// <summary> /// 上传图片 /// </summary> /// <param name="postedFile">文件</param> /// <param name="uploadPath">上传文件夹路径</param> ///<param name="maxSize">大小</param> /// <param name="thumbnail">是否生成缩略图</param> public UploadImageInfo UploadImage(HttpPostedFile postedFile, string uploadPath, int maxSize, bool thumbnail, int width = 0, int height = 0) { //上传配置 //string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; //文件允许格式 //string[] fileTypes = { "image/png", "image/bmp", "image/gif", "image/jpeg" }; //string uploadpath = HttpContext.Current.Server.MapPath(pathbase);//获取文件上传路径 try { var filepath = HttpContext.Current.Server.MapPath(uploadPath); //目录创建 if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } //string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; //文件允许格式 string[] filetype = { "image/png", "image/bmp", "image/gif", "image/jpeg" }; if (!filetype.Contains(postedFile.ContentType)) { upImage.msg = "图片格式错误"; } int fileSize = postedFile.ContentLength; //大小验证 if (fileSize >= maxSize * 1024 * 1024) { upImage.msg = string.Format("图片大小超出,请上传小于{0}M的图片", maxSize); } //保存图片 if (string.IsNullOrEmpty(upImage.msg)) { var oldName = postedFile.FileName; //获取文件扩展名称 string fileExt = Common.GetFileExt(oldName); //重命名文件 var newName = Common.Rename(oldName); //保存的路径 postedFile.SaveAs(filepath + newName); //生成缩略图 if (thumbnail) { string sFileName = "thumb_" + newName;//缩略图文件名 this.MakeThumbnail(filepath + newName, filepath + sFileName, width, height, ThumbnailType.WidthHeightCut); upImage.thumb = uploadPath + sFileName; //返回的小图 } upImage.status = (int)ResultCode.Success; upImage.msg = "上传成功"; upImage.name = oldName; upImage.path = uploadPath + newName; //返回的原图片URL upImage.size = fileSize; upImage.extension = fileExt; } else { upImage.status = (int)ResultCode.Fail; } } catch { upImage.status = (int)ResultCode.Fail; upImage.msg = "图片上传出错"; } return upImage; } /// <summary> /// 上传图片加水印 /// </summary> /// <param name="postedFile">文件</param> /// <param name="uploadPath">上传文件夹路径</param> /// <param name="maxSize">文件大小</param> /// <param name="waterType">水印类型</param> /// <param name="image_text">水印图片&水印文字</param> /// <param name="position">水印位置</param> /// <param name="thumbnail">是否生成缩略图</param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public UploadImageInfo UploadImage(HttpPostedFile postedFile, string uploadPath, int maxSize, WatermarkType waterType, string image_text, WatermarkPosition position, bool thumbnail, int width = 0, int height = 0) { try { var filepath = HttpContext.Current.Server.MapPath(uploadPath); //目录创建 if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; //文件允许格式 if (filetype.Contains(postedFile.ContentType)) { upImage.msg = "图片格式错误"; } int fileSize = postedFile.ContentLength; //大小验证 if (fileSize >= maxSize * 1024 * 1024) { upImage.msg = string.Format("图片大小超出,请上传小于{0}M的图片", maxSize); } //保存图片 if (string.IsNullOrEmpty(upImage.msg)) { var oldName = postedFile.FileName; //获取文件扩展名称 string fileExt = Common.GetFileExt(oldName); //重命名文件 var newName = Common.Rename(oldName); //创建图像流 Image img = Image.FromStream(postedFile.InputStream); if (waterType == WatermarkType.Text) { AddImageWaterMarkText(img, filepath + newName, image_text, (int)position, 90, "Verdana", 24); } else if (waterType == WatermarkType.Image) { if (!File.Exists(image_text)) { upImage.status = (int)ResultCode.Fail; upImage.msg = "水印图片不存在"; return upImage; } else { AddImageWaterMarkPic(img, filepath + newName, image_text, (int)position, 80, 10); } } if (thumbnail) { string sFileName = "thumb_" + newName;//缩略图文件名 this.MakeThumbnail(filepath + newName, filepath + sFileName, width, height, ThumbnailType.WidthHeightCut); upImage.thumb = uploadPath + sFileName; //返回的小图 } upImage.status = (int)ResultCode.Success; upImage.name = oldName; upImage.path = uploadPath + newName; //返回的原图片URL upImage.size = fileSize; upImage.extension = fileExt; } else { upImage.status = (int)ResultCode.Fail; } } catch { upImage.status = (int)ResultCode.Fail; upImage.msg = "图片上传出错"; } return upImage; } /// <summary> /// 加图片水印 /// </summary> /// <param name="img">要加水印的原图(System.Drawing)</param> /// <param name="filename">文件名</param> /// <param name="watermarkFilename">水印文件名</param> /// <param name="watermarkStatus">图片水印位置1=左上 2=中上 3=右上 4=左中 5=中中 6=右中 7=左下 8=中下 9=右下</param> /// <param name="quality">加水印后的质量0~100,数字越大质量越高</param> /// <param name="watermarkTransparency">水印图片的透明度1~10,数字越小越透明,10为不透明</param> public static void AddImageWaterMarkPic(Image img, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { Graphics g = Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Image watermark = new Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) return; ImageAttributes imageAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float transparency = 0.5F; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) transparency = (watermarkTransparency / 10.0F); float[][] colorMatrixElements = { new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; switch (watermarkStatus) { case 1: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case 2: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)(img.Height * (float).01); break; case 3: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)(img.Height * (float).01); break; case 4: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 5: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 6: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 7: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 8: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 9: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; } g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) ici = codec; } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) quality = 80; qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) img.Save(filename, ici, encoderParams); else img.Save(filename); g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); } /// <summary> /// 增加图片文字水印 /// </summary> /// <param name="img">要加水印的原图(System.Drawing)</param> /// <param name="filename">文件名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置1=左上 2=中上 3=右上 4=左中 5=中中 6=右中 7=左下 8=右中 9=右下</param> /// <param name="quality">加水印后的质量0~100,数字越大质量越高</param> /// <param name="fontname">水印的字体</param> /// <param name="fontsize">水印的字号</param> public static void AddImageWaterMarkText(Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { Graphics g = Graphics.FromImage(img); Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF crSize; crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.LightGray), xpos + 1, ypos + 1);//文字阴影 ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) ici = codec; } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) quality = 80; qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) img.Save(filename, ici, encoderParams); else img.Save(filename); g.Dispose(); img.Dispose(); } /// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> protected void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumbnailType type) { Image originalImage = Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; if (ow > oh) { type = ThumbnailType.Width; } else if (ow < oh) { type = ThumbnailType.Height; } switch (type) { case ThumbnailType.Width://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case ThumbnailType.Height://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case ThumbnailType.WidthHeightCut://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } #region 先上传再加水印 (已注释) ///// <summary> ///// 在图片上增加文字水印 ///// </summary> ///// <param name="Path">物理图片路径</param> ///// <param name="Path_sy">生成后带文字水印的图片路径</param> ///// <param name="waterText">水印文字</param> //protected void AddWaterText(string path, string savePath, string waterText) //{ // System.Drawing.Image image = System.Drawing.Image.FromFile(path); // System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); // g.DrawImage(image, 0, 0, image.Width, image.Height); // System.Drawing.Font f = new System.Drawing.Font("Verdana", 18); // System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White); // var x = image.Width * 0.4f; // var y = image.Height * 0.5f; // g.DrawString(waterText, f, b, x, y); // g.Dispose(); // image.Save(savePath); // image.Dispose(); //} ///// <summary> ///// 在图片上生成图片水印 ///// </summary> ///// <param name="Path">物理图片路径</param> ///// <param name="Path_syp">生成的带图片水印的图片路径</param> ///// <param name="Path_sypf">水印图片路径</param> //protected void AddWaterImage(string path, string savePath, string waterImage) //{ // System.Drawing.Image image = System.Drawing.Image.FromFile(path); // System.Drawing.Image copyImage = System.Drawing.Image.FromFile(waterImage); // System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); // g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width - 20, image.Height - copyImage.Height - 20, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel); // g.Dispose(); // image.Save(savePath); // image.Dispose(); //} #endregion }
UploadImageInfo.cs类
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// 上传图片 /// </summary> public class UploadImageInfo { /// <summary> /// 状态 /// </summary> public int status { get { return _status; } set { _status = value; } } private int _status = 0; /// <summary> /// 图片地址 /// </summary> public string path { get { return _path; } set { _path = value; } } private string _path = string.Empty; /// <summary> /// 缩略图地址 /// </summary> public string thumb { get { return _thumb; } set { _thumb = value; } } private string _thumb = string.Empty; /// <summary> /// 文件名 /// </summary> public string name { get { return _filename; } set { _filename = value; } } private string _filename = string.Empty; /// <summary> /// 文件大小 /// </summary> public int size { get { return _size; } set { _size = value; } } private int _size = 0; /// <summary> /// 消息 /// </summary> public string msg { get { return _msg; } set { _msg = value; } } private string _msg = string.Empty; /// <summary> /// 扩展名 /// </summary> public string extension { get { return _extension; } set { _extension = value; } } private string _extension = string.Empty; }
Common.cs类文件获取文件夹及扩展名
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; public class Common { #region /// <summary> /// 重命名文件 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string Rename(string fileName) { return DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000) + Path.GetExtension(fileName); } /// <summary> /// 获取文件名称 /// </summary> public static string GetFileExt(string fileName) { return Path.GetExtension(fileName); } #endregion }
Enums.cs 类文件配置类型情况
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// 图片分类 /// </summary> public enum ImageCategory { /// <summary> /// 无 /// </summary> None = 0, /// <summary> /// banner /// </summary> Banner = 1, /// <summary> /// 新闻 /// </summary> Article = 2, /// <summary> /// 商品 /// </summary> Product = 3, } /// <summary> /// 生成缩略图类型 /// </summary> public enum ThumbnailType { /// <summary> /// 指定高宽缩放(可能变形) /// </summary> WidthHeight = 0, /// <summary> /// 指定宽,高按比例(不变形) /// </summary> Width = 1, /// <summary> /// 指定高,宽按比例(不变形) /// </summary> Height = 2, /// <summary> /// 指定高宽裁减(不变形) /// </summary> WidthHeightCut = 3, /// <summary> /// 指定高宽范围(不变形) /// </summary> WidthHeightAuto = 4, } /// <summary> /// 水印类型 /// </summary> public enum WatermarkType { /// <summary> /// 文字 /// </summary> Text = 0, /// <summary> /// 图片 /// </summary> Image = 1 } /// <summary> /// 水印定位 /// </summary> public enum WatermarkPosition { /// <summary> /// 左上角 /// </summary> TopLeft = 1, /// <summary> /// 中上 /// </summary> TopCenter = 2, /// <summary> /// 右上角 /// </summary> TopRight = 3, /// <summary> /// 左中 /// </summary> CenterLeft = 4, /// <summary> /// 中心 /// </summary> Center = 5, /// <summary> /// 右中 /// </summary> CenterRigth = 6, /// <summary> /// 左下角 /// </summary> BottomLeft = 7, /// <summary> /// 中下 /// </summary> BottomCenter = 8, /// <summary> /// 右下角 /// </summary> BottomRight = 9, } /// <summary> /// 返回状态 /// </summary> public enum ResultCode { /// <summary> /// 失败0 /// </summary> Fail = 0, /// <summary> /// 成功1 /// </summary> Success = 1, }