How to zoom an image in&out in C#?

63,112

One solution is:

  1. Create new image of the desired size (for example 200% or 50% of original image size)
  2. Draw original image to new image using Graphics.DrawImage(Image, Rectangle);, which draws the given image to the new image at the given position with the given size
  3. Set new image as source for the PictureBox

Another way is to simple create a new bitmap instance like that:

Size newSize = new Size((int)(originalBitmap.Width * zoomFactor), (int)(originalBitmap.Height * zoomFactor));
Bitmap bmp = new Bitmap(originalBitmap, newSize);
Share:
63,112
Mehmet Ince
Author by

Mehmet Ince

A software developer

Updated on July 09, 2022

Comments

  • Mehmet Ince
    Mehmet Ince almost 2 years

    I want to implement zoom for an image. I don't want to resize the PictureBox, but the image itself.

    How do I do this?

  • CoreModule
    CoreModule almost 12 years
    Don't forget to add scrollbars to scroll the image
  • Thorsten Dittmar
    Thorsten Dittmar almost 12 years
    @PoweRoy is right - best: put the PictureBox into a ScrollView. This is hassle-free.
  • OPV
    OPV over 6 years
    How is changed grid of imge after zooming? Does it mean, that coordinates of pixels are changes?
  • Thorsten Dittmar
    Thorsten Dittmar over 6 years
    @OPV Not really sure what you mean. The source image is resampled to match the new size. This means that if you reduce the size, you lose pixels and if you increase the size pixels need to be doubled (good algorithms interpolate here). In any case you lose the original image information, which means that you will need to keep a reference to the original image if you want to allow the user to zoom in and out and in and out again. Otherwise you resample a previously resampled image, which will look ugly.