Resizing Bitmap Images in C# and WPF

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:

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

scaleX and scaleY should be the scale by which you want to resize the image. In my case, I was shrinking an image from 32×32 to 16×16, 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:

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:

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

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

  • Elyo Martinez

    Hi, thanks for sharing your solution.

    I have a question, how do i get the IntPtr from the image i want to use? (The first parameter in CreateBitmapSourceFromHBitmap).

    For example, if my image is in the path: C:\Users\emartinez\Pictures\temp\image1.jpg , how do i get that parameter?


    • Ian Rufus

      Hi Elyo, thanks for the comment!
      Sorry for the late reply – your comment was buried under dozens of spam comments.

      The way I did it when I came across this was to add the image to the resources of the project, you can then access it as described in this post.
      If it’s an external image you’re after, you should be able to load the file into a Bitmap object, and get the IntPtr from there as described in this SO question:

      Hope that helps!