保持比例图像缩放简易算法,关键字(C#,.Net,图片,缩放,比例)
最近忙X-Library,图形处理做得比较多。有很多时候都需要生成缩略图,可是如何在不扯宽或扯高原图的基础上,动态的生成缩略图就遇到了问题。
例如(单位像素px):
原图宽高为 1117x1100,要求生成宽高范围在128x96的缩略图。
以前就是粗糙的写死缩略图宽高,指定为128x96,生成的缩略图就会变形,十分难看。
今天上午在网上找了一圈,没有发现现成的代码,只好抽了点时间,写了个简易动态算法,根据原图/ 缩略图长宽比来判断,动态生成缩略图的长和宽。
如下:
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; }