今天就跟大家聊聊有关Asp.net mvc中怎么实时生成缩率图,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
创新互联公司长期为成百上千客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为景东企业提供专业的成都做网站、成都网站制作、成都外贸网站建设,景东网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。思路很简单,就是根据请求,判断需要的缩率图是否已存在于硬盘上,如果有直接返回,没有则下载原图,并生成缩率图到本地,返回给客户端。
下面直接粘贴代码片段:
////// 生成图片缩率图Action /// /// 原图url /// 图片尺寸以及生成缩率图的类型 ///[ValidateInput(false)] public ActionResult Index(string p, string id) { if (string.IsNullOrEmpty(p)) { return new HttpStatusCodeResult(404); } string oPath = Regex.Replace(p, @"http[s]?://(.*?)/", "/", RegexOptions.IgnoreCase); int? oWidth = 200, oHeight = 200; int cutMode = 3; string pPath; string oDir; if (!string.IsNullOrEmpty(id)) { string[] ss = id.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries); if (ss.Length < 2) { return new HttpStatusCodeResult(404); } if (ss.Length > 2) { cutMode = int.Parse(ss[2]); } oPath = oPath.Insert(oPath.LastIndexOf('/') + 1, string.Format("{0}_{1}_{2}_", ss[0], ss[1], cutMode)); oWidth = int.Parse(ss[0]); oHeight = int.Parse(ss[1]); } pPath = Server.MapPath(oPath); oDir = Path.GetDirectoryName(pPath); if (!System.IO.File.Exists(pPath)) { byte[] imagebytes = FileHelper.DownLoadFile(p); if (!Directory.Exists(oDir)) { Directory.CreateDirectory(oDir); } FileHelper.MakeThumbnail(FileHelper.BytToImg(imagebytes), oWidth.Value, oHeight.Value, (ThumbnailMode)cutMode, pPath, true); } return File(pPath, FileHelper.GetContentTypeByExtension(Path.GetExtension(pPath).ToLower())); }
辅助方法:
public class FileHelper { ////// 图片后缀和ContentType对应字典 /// static DictionaryextensionContentTypeDic; static FileHelper() { if (extensionContentTypeDic == null) { //.jpg", ".png", ".gif", ".jpeg extensionContentTypeDic = new Dictionary (); extensionContentTypeDic.Add(".jpg", "image/jpeg"); extensionContentTypeDic.Add(".png", "image/png"); extensionContentTypeDic.Add(".gif", "image/gif"); extensionContentTypeDic.Add(".jpeg", "image/jpeg"); } } /// /// 根据后缀名获取extension /// /// ///public static string GetContentTypeByExtension(string extension) { if (extensionContentTypeDic.ContainsKey(extension)) { return extensionContentTypeDic[extension]; } return null; } /// /// 将Image对象转化成二进制流 /// /// ///public static byte[] ImageToByteArray(Image image) { MemoryStream imageStream = new MemoryStream(); Bitmap bmp = new Bitmap(image.Width, image.Height); Graphics g = Graphics.FromImage(bmp); g.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height)); try { bmp.Save(imageStream, image.RawFormat); } catch (Exception e) { bmp.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); } byte[] byteImg = imageStream.GetBuffer(); bmp.Dispose(); g.Dispose(); imageStream.Close(); return byteImg; } /// /// 字节流转换成图片 /// /// 要转换的字节流 ///转换得到的Image对象 public static Image BytToImg(byte[] byt) { MemoryStream ms = new MemoryStream(byt); Image img = Image.FromStream(ms); ms.Close(); return img; } ////// 生成缩率图 /// /// 原始图片Image /// 缩率图宽 /// 缩率图高 /// 生成缩率图的方式 /// 缩率图存放的地址 public static Image MakeThumbnail(Image originalImage, int width, int height, ThumbnailMode mode, string thumbnailPath, bool isSave = true) { int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case ThumbnailMode.HW://指定高宽缩放(可能变形) break; case ThumbnailMode.W://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case ThumbnailMode.H://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case ThumbnailMode.Cut://指定高宽裁减(不变形) 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图片 System.Drawing.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); if (!isSave) { return bitmap; } try { //以jpg格式保存缩略图 //bitmap.Save(thumbnailPath, bitmap.RawFormat); bitmap.Save(thumbnailPath, ImageFormat.Jpeg); return bitmap; } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } return null; } ////// 下载指定文件 /// /// /// public static byte[] DownLoadFile(string remoteUrl) { WebClient wc = new WebClient(); try { return wc.DownloadData(remoteUrl); } catch (Exception e) { throw new Exception("下载文件失败"); } } } public enum ThumbnailMode { ////// 指定高宽缩放(可能变形) /// HW, ////// 指定高,宽按比例 /// H, ////// 指定宽,高按比例 /// W, ////// 指定高宽裁减(不变形) /// Cut, }
访问方式:
/tupian/20230522/{width}_{height}_{ThumMode} 1:指定高宽按比例、2:指定宽,高按比例、3:指定高宽裁减(不变形)
{Width}:期望图片宽
{Height}:期望图片高
看完上述内容,你们对Asp.net mvc中怎么实时生成缩率图有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。