C# 图片等比例不丢真缩放
2016-03-28 22:43
597 查看
1.参考文献:http://blog.itpub.net/631872/viewspace-1049782/
2.实现方法:
2.实现方法:
//使用方法调用GenerateHighThumbnail()方法即可 //参数oldImagePath表示要被缩放的图片路径 //参数newImagePath表示缩放后保存的图片路径 //参数width和height分别是缩放范围宽和高 public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height) { System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath); int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width; int newHeight =AdjustSize(width, height, oldImage.Width, oldImage.Height).Height; //。。。。。。。。。。。 System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight,new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage); //处理JPG质量的函数 System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); if (ici != null) { System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1); ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); bm.Save(newImagePath, ici, ep); //释放所有资源,不释放,可能会出错误。 ep.Dispose(); ep = null; } ici = null; bm.Dispose(); bm = null; thumbnailImage.Dispose(); thumbnailImage = null; oldImage.Dispose(); oldImage = null; } private static bool ThumbnailCallback() { return false; } private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } public struct PicSize { public int Width; public int Height; } public static PicSize AdjustSize(int spcWidth, int spcHeight, int orgWidth, int orgHeight) { PicSize size = new PicSize(); // 原始宽高在指定宽高范围内,不作任何处理 if (orgWidth <= spcWidth && orgHeight <= spcHeight) { size.Width = orgWidth; size.Height = orgHeight; } else { // 取得比例系数 float w = orgWidth / (float)spcWidth; float h = orgHeight / (float)spcHeight; // 宽度比大于高度比 if (w > h) { size.Width = spcWidth; size.Height = (int)(w >= 1 ? Math.Round(orgHeight / w) : Math.Round(orgHeight * w)); } // 宽度比小于高度比 else if (w < h) { size.Height = spcHeight; size.Width = (int)(h >= 1 ? Math.Round(orgWidth / h) : Math.Round(orgWidth * h)); } // 宽度比等于高度比 else { size.Width = spcWidth; size.Height = spcHeight; } } return size; }
相关文章推荐
- C#打印PDF
- C#中设置console和form同时显示
- 关于c#的webbrows控件自动填写表单并获取提交后的网页内容
- C#的Socket编程基础
- C#事件
- C#多态
- C#进阶系列——WebApi身份认证解决方案:Basic基础认证 (转)
- 【C#学习路途】被数学老师罚,确让我机智的挡住了惩罚,功劳全靠程序!
- 不分组求和(Linq、存储过程)
- C#高级编程四十九天----队列
- SM C#实现
- C#并行编程--命令式数据并行(Parallel.Invoke)---与匿名函数一起理解(转载整理)
- c#学习之三:抽象类,密封类和类成员
- C#使用正则表达式检测数字 char 和韩文
- C#调用Exe程序示例
- C#实现在图片上斜着写字
- C# 线程的各种知识,和使用方法
- C# 如何执行bat文件 传参数
- 02章《深入C#数据类型》项目经理评分
- 二叉树的存储结构