How to zoom an image in&out in C#?
Asked Answered
P

2

21

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?

Piscine answered 6/6, 2012 at 14:11 Comment(0)
R
37

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);
Ranchman answered 6/6, 2012 at 14:15 Comment(4)
Don't forget to add scrollbars to scroll the imageSisk
@PoweRoy is right - best: put the PictureBox into a ScrollView. This is hassle-free.Ranchman
How is changed grid of imge after zooming? Does it mean, that coordinates of pixels are changes?Rigorous
@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.Ranchman
D
2

I used a web browser to achieve this.

//loads the image
myWebBrowser.Navigate(@"C:\myimage.png");

From there I used SendKeys to zoom in and out

myWebBrowser.Select(); //Selects browser.
SendKeys.Send("^{+}"); //Sends the control + key combo, causing the browser to zoom in. Replace the "+" with a "-" to zoom out.

It's a bit of a weird method, but it worked really well for me. I hope you find this helpful!

Dobruja answered 20/6, 2019 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.