Resizing Bitmap Images in C# and WPF


I found myself needing to resize a bitmap image I have in the resources of my project, and apply the resized image to a button. A quick Google found some suggestions, but no clear way of doing so - as such, I thought I’d show my solution here.

The first step is to get the BitmapSource from the Bitmap image you have in the resources file:

BitmapSource newBitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
		IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

Using this BitmapSource we can then use TransformedBitmap to get a new scaled Bitmap, like so:

var resizedBitmap = new TransformedBitmap(newBitmapSource, new ScaleTransform(scaleX,scaleY));

scaleX and scaleY should be the scale by which you want to resize the image. In my case, I was shrinking an image from 32x32 to 16x16, so both variables were set to 0.5d

To set a new image for a button it needs to be done as the Background, which requires it to be an Image Brush. So now we need to create a new ImageBrush and set the ImageSource to our resized image:

var brush = new ImageBrush();
brush.ImageSource = resizedBitmap;

Another thing to note is that when creating a new Brush, the Stretch property will default to Fill. This may be ok, but if like me you wanted the image to stay centred and small, simply set the property to None:

brush.Stretch = Stretch.None;

Then simply set the Background property of your button (or other control) to this new brush:

btnClickMe.Background = brush;

And that’s it, the image is resized in the code and applied to the button!

comments powered by Disqus