日期:2014-05-18 浏览次数:20433 次
//代码摘自网络,自己定义个类,将相关代码放进去即可使用 enum Dimensions { Width, Height } enum AnchorPosition { Top, Center, Bottom, Left, Right } static Image ScaleByPercent(Image imgPhoto, int Percent) { float nPercent = ((float)Percent/100); int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX,destY,destWidth,destHeight), new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; } static Image ConstrainProportions(Image imgPhoto, int Size, Dimensions Dimension) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; switch(Dimension) { case Dimensions.Width: nPercent = ((float)Size/(float)sourceWidth); break; default: nPercent = ((float)Size/(float)sourceHeight); break; } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX,destY,destWidth,destHeight), new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); return bmPhoto; } static Image FixedSize(Image imgPhoto, int Width, int Height) { int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)Width/(float)sourceWidth); nPercentH = ((float)Height/(float)sourceHeight); //if we have to pad the height pad both the top and the bottom //with the difference between the scaled height and the desired height if(nPercentH < nPercentW) { nPercent = nPercentH;