Asp.Net 上传图片并根据json参数生成缩略图
在asp.net中,上传图片功能或者是常用的,生成缩略图也是常用的
生成图片缩略图帮助类:
public enum ThumbnailMode { /// <summary> /// 指定高宽缩放(可能变形) /// </summary> FixedHeightWidth, /// <summary> /// 指定宽度,高度按比例自动计算 /// </summary> WidthBased, /// <summary> /// 指定高度,宽度按比例自动计算 /// </summary> HeightBased, /// <summary> /// 指定高宽裁减(从Width,Height处开始裁剪,不变形) /// </summary> /// KeepAspectRatio, } class ImageHelperException : Exception { public readonly string ErrorCode; public ImageHelperException(string errorCode, string message) : base(message) { ErrorCode = errorCode; } } public class ImageHelper { public static Image GetThumbnail(Image sourceImage, int width, int height, ThumbnailMode mode) { int originalWidth = sourceImage.Width; int originalHeight = sourceImage.Height; int thumbnailWidth, thumbnailHeight; int cropWidth=sourceImage.Width; int cropHeight=sourceImage.Height; double ratio; switch (mode) { case ThumbnailMode.FixedHeightWidth: thumbnailWidth = width; thumbnailHeight = height; break; case ThumbnailMode.WidthBased: thumbnailWidth = width; ratio = (double)width / originalWidth; thumbnailHeight = Convert.ToInt32(originalHeight * ratio); if (thumbnailHeight == 0) thumbnailHeight = 1; break; case ThumbnailMode.HeightBased: thumbnailHeight = height; ratio = (double)height / originalHeight; thumbnailWidth = Convert.ToInt32(originalWidth * ratio); if (thumbnailWidth == 0) thumbnailWidth = 1; break; case ThumbnailMode.KeepAspectRatio: thumbnailHeight = height; thumbnailWidth = width; float thumbRaitio = (float)thumbnailWidth / (float)thumbnailHeight; float origRatio = (float)originalWidth / (float)originalHeight; if (thumbRaitio < origRatio) { //原图宽 cropWidth = (int)(originalHeight * thumbRaitio); } else { cropHeight = (int)(originalWidth / thumbRaitio); //小图宽 } break; default: throw new ImageHelperException("99", "Invalid Thumbnail Mode"); } Graphics g = null; try { //新建一个bmp图片 Image thumbnail = new Bitmap(thumbnailWidth, thumbnailHeight); //新建一个画板 g = Graphics.FromImage(thumbnail); //设置高质量插值法 g.InterpolationMode = InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 Rectangle rectThumbnail = new Rectangle(0, 0, thumbnailWidth, thumbnailHeight); Rectangle rectSelection = new Rectangle(0, 0, originalWidth, originalHeight); if (mode == ThumbnailMode.KeepAspectRatio) { rectSelection = new Rectangle((originalWidth - cropWidth) / 2, (originalHeight - cropHeight) / 2, cropWidth, cropHeight); } g.DrawImage(sourceImage, rectThumbnail, rectSelection, GraphicsUnit.Pixel); return thumbnail; } finally { if (g != null) g.Dispose(); } } /// <summary> /// Get Thumbnail from file /// </summary> /// <param name="fileName"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="mode"></param> /// <returns>Image</returns> public static Image GetThumbnail(string fileName, int width, int height, ThumbnailMode mode) { Image img = Image.FromFile(fileName); return GetThumbnail(img, width, height, mode); } /// <summary> /// Get thumbnail from image and save thumbnail /// </summary> /// <param name="sourceImage"></param> /// <param name="destFileName"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="mode"></param> public static void GetThumbnail(Image sourceImage, string destFileName, int width, int height, ThumbnailMode mode, ImageFormat saveFormat) { Image thumbnailcopy = GetThumbnail(sourceImage, width, height, mode); Image thumbnail = new Bitmap(thumbnailcopy); thumbnailcopy.Dispose(); try { thumbnail.Save(destFileName, saveFormat); } finally { thumbnail.Dispose(); } } /// <summary> /// Get thumbnail from file and save thumbnail /// </summary> /// <param name="sourceFileName">source image file name</param> /// <param name="destFileName">file name to save thumbnail</param> /// <param name="width">width of thumbnail</param> /// <param name="height">height of thumbnail</param> /// <param name="mode">mode</param> public static void GetThumbnail(string sourceFileName, string destFileName, int width, int height, ThumbnailMode mode, ImageFormat saveFormat) { Image img = Image.FromFile(sourceFileName); GetThumbnail(img, destFileName, width, height, mode, saveFormat); } /// <summary> /// Get thumbnail with specified region from image /// </summary> /// <param name="sourceImage">source image</param> /// <param name="offsetX">x offset in source image</param> /// <param name="offsetY">y offset in source image</param> /// <param name="width">width of thumbnail</param> /// <param name="height">height of thumbnail</param> /// <returns></returns> public static Image GetThumbnail(Image sourceImage, int offsetX, int offsetY, int width, int height) { Image thumbnail = new Bitmap(width, height); Graphics g = null; try { //新建一个画板 g = Graphics.FromImage(thumbnail); //设置高质量插值法 g.InterpolationMode = InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 Rectangle rectThumbnail = new Rectangle(0, 0, width, height); Rectangle rectSelection = new Rectangle(offsetX, offsetY, width, height); g.DrawImage(sourceImage, rectThumbnail, rectSelection, GraphicsUnit.Pixel); return thumbnail; } finally { if (g != null) g.Dispose(); } } /// <summary> /// Get thumbnail with specified region from file /// </summary> /// <param name="sourceFileName">source image file name</param> /// <param name="offsetX">x offset in source image</param> /// <param name="offsetY">y offset in source image</param> /// <param name="width">width of thumbnail</param> /// <param name="height">height of thumbnail</param> /// <returns></returns> public static Image GetThumbnail(string sourceFileName, int offsetX, int offsetY, int width, int height) { Image img = Image.FromFile(sourceFileName); return GetThumbnail(img, offsetX, offsetY, width, height); } /// <summary> /// Get thumbnail with specified region from image and save to file /// </summary> /// <param name="sourceImage">source image</param> /// <param name="offsetX">x offset in source image</param> /// <param name="offsetY">y offset in source image</param> /// <param name="width">width of thumbnail</param> /// <param name="height">height of thumbnail</param> /// <returns></returns> public static void GetThumbnail(Image sourceImage, string destFileName, int offsetX, int offsetY, int width, int height, ImageFormat saveFormat) { Image thumbnail = GetThumbnail(sourceImage, offsetX, offsetY, width, height); try { thumbnail.Save(destFileName, saveFormat); } finally { thumbnail.Dispose(); } } /// <summary> /// Get thumbnail with specified region from file and save to file /// </summary> /// <param name="sourceFileName">source image file name</param> /// <param name="destFileName">file name to save thumbnail</param> /// <param name="offsetX">x offset in source image</param> /// <param name="offsetY">y offset in source image</param> /// <param name="width">width of thumbnail</param> /// <param name="height">height of thumbnail</param> /// <returns></returns> public static void GetThumbnail(string sourceFileName, string destFileName, int offsetX, int offsetY, int width, int height, ImageFormat saveFormat) { Image img = Image.FromFile(sourceFileName); GetThumbnail(img, destFileName, offsetX, offsetY, width, height, saveFormat); } public static void GetImageSize(string fileName, out int width, out int height) { Image img = Image.FromFile(fileName); width = img.Width; height = img.Height; } }
后台代码调用帮助类方法:
try { if (this.flUpload.PostedFile.FileName == "") { this.cvPage.ErrorMessage = "请选择上传文件"; this.cvPage.IsValid = false; return; } string pPath = ConfigurationManager.AppSettings["UserDataPath"] + "\\Upload\\"; //C:\MyProjects\xframework3.cms\src\XFCMSSln\ExtModuleCMSWeb\UserData\Upload\ string fileName = DateTime.Now.Ticks.ToString();//重新给图片命名 string updFileName = this.flUpload.PostedFile.FileName;//图片名称 string ext = updFileName.Substring(updFileName.LastIndexOf(".")); this.flUpload.PostedFile.SaveAs(pPath + fileName + ext);//保存图片 string originalPath = pPath + fileName + ext;//原图片 int fieldDefinitionId = Convert.ToInt32(Request.QueryString["FieldDefinitionId"]); FieldDefinitionDao dao = new FieldDefinitionDao(XFMainApplication.Instance.HibSessions); CMS_FieldDefinition fieldDefinition = dao.GetFieldDefinition("where FieldDefinitionID=" + fieldDefinitionId)[0] as CMS_FieldDefinition; string ImgResizeParm = fieldDefinition.ImgResizeParm;//参数 string resize = fieldDefinition.IsImgResize; //是否缩略 if (resize == "Y") { //string thumbnailfileName;//缩略图片名称 //ImageResizeModel iRm = new ImageResizeModel(); //iRm.ImageResizeParms = JsonConvert.DeserializeObject<List<ImageResizeParm>>(ImgResizeParm); //ImageResizeModel mdlParm = new ImageResizeModel(); //ImageResizeModel mdlParm = JsonConvert.DeserializeObject<ImageResizeModel>(ImgResizeParm);//转为json对象 ImageResizeModel mdlParm = (ImageResizeModel)JsonConvert.DeserializeObject(ImgResizeParm, typeof(ImageResizeModel)); if (mdlParm.ImageResizeParms != null)//判断集合了里面是否有数据 { foreach (var item in mdlParm.ImageResizeParms) { //thumbnailfileName = DateTime.Now.Ticks.ToString();//循环生成缩略图片名称 string FolderName = item.FolderName; string thumbnailPuffPath = Path.Combine(pPath, FolderName);//原图片加文件夹名称,缩略图片路径 if (!System.IO.File.Exists(thumbnailPuffPath)) { Directory.CreateDirectory(thumbnailPuffPath);//创建文件夹 } string thumbnailPuffPaths = Path.Combine(thumbnailPuffPath, fileName + ext); int wigth = item.Width; int hight = item.Height; ImageHelper.GetThumbnail(originalPath, thumbnailPuffPaths, wigth, hight, ThumbnailMode.KeepAspectRatio, ImageFormat.Jpeg); } } else { this.lblmessage.Text = "对象为空"; //Response.Write("<script language='javascript'>alert('对象是空')</script>"); } } else { this.flUpload.PostedFile.SaveAs(pPath + fileName + ext);//保存图片 } string vPath = ConfigurationManager.AppSettings["UserDataUrl"] + "/Upload/";//"../System/Upload/"; string script = "<script language='javascript'>window.opener.aspnetForm." + Request.QueryString["fieldName"] + ".value = '" + vPath + fileName + ext + "';window.close();</script>"; Response.Write(script); } catch (Newtonsoft.Json.JsonReaderException) { this.lblmessage.Text = "Json数据格式不对"; } catch (Newtonsoft.Json.JsonSerializationException) { this.lblmessage.Text = "Json数据格式不对,导致解析不对"; } catch (Exception ex) { this.lblmessage.Text = ex.Message; //this.Page.ClientScript.RegisterClientScriptBlock(GetType(), "scriptSessionLost", "alert('操作失败,数据格式不正确,请重试!');", true); }
清空回声
浙公网安备 33010602011771号