Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 0.82 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio
  2. float width = 1024;
  3. float height = 768;
  4. var brush = new SolidBrush(Color.Black);
  5.        
  6. var image = new Bitmap(file);
  7.        
  8. float scale = Math.Min(width / image.Width, height / image.Height);
  9.        
  10. var bmp = new Bitmap((int)width, (int)height);
  11. var graph = Graphics.FromImage(bmp);
  12.  
  13. // uncomment for higher quality output
  14. //graph.InterpolationMode = InterpolationMode.High;
  15. //graph.CompositingQuality = CompositingQuality.HighQuality;
  16. //graph.SmoothingMode = SmoothingMode.AntiAlias;
  17.  
  18. var scaleWidth = (int)(image.Width * scale);
  19. var scaleHeight = (int)(image.Height * scale);
  20.  
  21. graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
  22. graph.DrawImage(image, new Rectangle(((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight));