public static ImageSize Generate(uint PixelsCount, double MaximumDeltaPercent=1f, uint MaximumAbsoluteDelta=10, double MaximumAspectRatio=1.77) { //check if this is empty image if (PixelsCount==0) return new ImageSize(1,1); //check if this is a square double sqrt = Math.Truncate(Math.Sqrt(PixelsCount)); if (Math.Pow(sqrt, 2) == PixelsCount) return new ImageSize((ushort)sqrt, (ushort) sqrt); // , AspectRatio - , . . if (PixelsCount<=10) MaximumAspectRatio = double.MaxValue; double percentdelta = PixelsCount/(MaximumDeltaPercent*100); uint height = (ushort) Math.Truncate(Math.Sqrt(PixelsCount)); uint width = (ushort) (height+1); while (width/(height*1.0f)<MaximumAspectRatio) { ulong Result = width*height; if (Result==PixelsCount) { if (width<=ushort.MaxValue && height<=ushort.MaxValue) { return new ImageSize((ushort) width, (ushort) height); } } if (Result>PixelsCount) { if ((Result-PixelsCount)<=percentdelta || Result-PixelsCount<=MaximumAbsoluteDelta) { if (width <= ushort.MaxValue && height <= ushort.MaxValue) { return new ImageSize((ushort) width, (ushort) height); } } height--; continue; } if (Result < PixelsCount) { width++; } } throw new Exception(string.Format(" {0} Aspect Ratio. \n : PC:{0} MDP:{1} MAD:{2} MAR{3}",PixelsCount,MaximumDeltaPercent,MaximumAbsoluteDelta,MaximumAspectRatio)); }
Source: https://habr.com/ru/post/214165/
All Articles