View Light

HOWTO: Resize a bitmap smoothly

This is an improvement to a ResizeBitmap method that's floating around the net. The original works quickly and reliably, but when you use it to shrink bitmaps down to a thumbnail size, it produces grainy output. Shrunken text becomes near unreadable.

The original code is as follows, I do not have any info about who originally wrote it, but I didn't:

public Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight )
      Bitmap result = new Bitmap( nWidth, nHeight );  
      using( Graphics g = Graphics.FromImage( (Image) result ) )    
          g.DrawImage( b, 0, 0, nWidth, nHeight );  
      return result;

This code was slightly tweaked to use Bicubic Interpolation during the resize, which outputs a much smoother/softer bitmap, usually preserving the readability of any shrunken text. (Shrink it too much and any text becomes unreadable, but this at least lets you shrink a bitmap considerably further.) It's only a one-line change, so this isn't anything of a killer hack, but it really helps the output quality a lot, so thought I'd share.

private Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
      Bitmap result = new Bitmap(nWidth, nHeight);
      using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(b, 0, 0, nWidth, nHeight);
      return result;

Note that for the above code sample, you need the following namespaces included:

using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

Rating: (You must be logged in to vote)
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.