public static Image ResizeImageForCognitiveOCR(Image image)//, int width, int height) { // If image is less than 3200x3200 return it if (image.Height <= 4200 && image.Width <= 4200) { return(image); } // Rescale the image for max 3150 x 3150 (below 3200 x 3200) var originalWidth = image.Size.Width; var originalHeight = image.Size.Height; var width = 4000; var height = 4000; // Figure out the ratio double ratioX = (double)width / (double)originalWidth; double ratioY = (double)height / (double)originalHeight; // use whichever multiplier is smaller double ratio = ratioX < ratioY ? ratioX : ratioY; // now we can get the new height and width int newHeight = Convert.ToInt32(originalHeight * ratio); int newWidth = Convert.ToInt32(originalWidth * ratio); var destRect = new Rectangle(0, 0, newWidth, newHeight); var destImage = new Bitmap(newWidth, newHeight); // Now calculate the X,Y position of the upper-left corner // (one of these will always be zero) int posX = Convert.ToInt32((newWidth - (originalWidth * ratio)) / 2); int posY = Convert.ToInt32((newHeight - (originalHeight * ratio)) / 2); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; //graphics.CompositingQuality = CompositingQuality.HighQuality; //graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; //graphics.SmoothingMode = SmoothingMode.HighQuality; //graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.ClearBrushRemapTable(); wrapMode.ClearGamma(); wrapMode.ClearColorMatrix(); wrapMode.SetWrapMode(WrapMode.Tile); graphics.Clear(Color.White); //graphics.DrawRectangle(new Pen(new SolidBrush(Color.White)), 0, 0, newWidth, newHeight); graphics.DrawImage(image, destRect, posX, posY, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } // Ensure image doesn't have a transparency layer Bitmap temp = new Bitmap(destImage.Width, destImage.Height, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(temp); g.Clear(Color.White); g.DrawImage(destImage, Point.Empty); return(temp); // return destImage; }