asp.net – MVC3 WebImage助手:resize将透明背景转换为黑色
发布时间:2020-12-15 20:50:49 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用MVC3的Web Image助手创建缩略图. 原始图像是具有透明背景的.png.当我尝试使用以下内容调整大小时: var image = blob.DownloadByteArray(); new WebImage(image) .Resize(50,50) .Write(); 生成的缩略图将原始透明背景替换为黑色背景. 解决方
我正在尝试使用MVC3的Web
Image助手创建缩略图.
原始图像是具有透明背景的.png.当我尝试使用以下内容调整大小时: var image = blob.DownloadByteArray(); new WebImage(image) .Resize(50,50) .Write(); 生成的缩略图将原始透明背景替换为黑色背景. 解决方法
上面这个答案很棒,但我做了一些微调并实现了图像的“保持比例”,这样我们就不会得到拉伸的图像了.
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Web.Helpers; public static class ResizePng { private static IDictionary<string,ImageFormat> _transparencyFormats = new Dictionary<string,ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png",ImageFormat.Png },{ "gif",ImageFormat.Gif } }; public static WebImage ResizePreserveTransparency(this WebImage image,int width,int height) { ImageFormat format = null; if (!_transparencyFormats.TryGetValue(image.ImageFormat,out format)) { return image.Resize(width,height); } //keep ratio ************************************* double ratio = (double)image.Width / image.Height; double desiredRatio = (double)width / height; if (ratio > desiredRatio) { height = Convert.ToInt32(width / ratio); } if (ratio < desiredRatio) { width = Convert.ToInt32(height * ratio); } //************************************************ using (Image resizedImage = new Bitmap(width,height)) { using (Bitmap source = new Bitmap(new MemoryStream(image.GetBytes()))) { using (Graphics g = Graphics.FromImage(resizedImage)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(source,width,height); } } using (MemoryStream ms = new MemoryStream()) { resizedImage.Save(ms,format); return new WebImage(ms.ToArray()); } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 单元测试 – 测试ASP.NET Web API多部分表单数据文件上载
- asp.net-mvc – ASP.NET MVC 4,如何在将视图模型对象用作动
- asp.net-mvc – 如何阻止URL.Action包含参数?
- asp.net-mvc – 从n层ASP.Net MVC应用程序的服务层处理或抛
- ASP.NET-MVC 2 RC最佳功能
- asp.net – 对数据绑定集合或对象列表时对gridview进行排序
- 使用.net数据注释验证颜色(十六进制值)
- asp.net-mvc – Firefox在Ajax请求重定向期间不保留自定义标
- MVC3 .NET会话随机丢失会话值并返回null
- asp.net-mvc – 如何使用ASP.NET MVC实现自定义缓存提供程序
推荐文章
站长推荐
- asp.net – 元素> system.webServer’有无效的ch
- asp.net – 在SQL Server中只获取浮点数的小数部
- ASP.NET获取请求的url信息汇总
- asp.net – 使用Spark视图引擎在局部视图中使用不
- 本地化 – 当我将文化添加到文件名时,我的全局资
- ASP.NET Web Api中的Swashbuckle被嵌套控制器搞糊
- asp.net-mvc – System.NotSupportedException:
- asp.net – Mysql中int(10)的最大大小是多少?
- asp.net-mvc – 如何将httppostedfilebase转换为
- asp.net-mvc – 将ASP.NET MVC应用程序部署到IIS
热点阅读