HOWTO: Resize a bitmap smoothly
Posted: 3/30/2007 12:00:22 PMBy: Comfortably Anonymous
Times Read: 2,623
Likes: 0 Dislikes: 0
Topic: Programming: .NET Framework
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;
Enjoy!
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;
Enjoy!
Rating: (You must be logged in to vote)