Emulate Image Zooming in a PictureBox Control at Runtime

Posted by: Suprotim Agarwal , on 9/1/2008, in Category WinForms & WinRT
Views: 64559
Abstract: Zooming images in a PictureBox control is not something that comes out of the box. However with a little bit of code, basic emulation of zoom in and zoom out functionality can be achieved quiet easily. In this article, we will explore how to emulate zoom-in and zoom-out, of an image kept in the PictureBox control.
Emulate Image Zooming in a PictureBox Control at Runtime
 
Zooming images in a PictureBox control is not something that comes out of the box. However with a little bit of code, basic emulation of zoom in and zoom out functionality can be achieved quiet easily. In this article, we will explore how to emulate zoom in and zoom out, on an image kept in the PictureBox control. Please follow these steps:
Step 1: Open Visual Studio > File > New > Project. In the Project Types pane, choose the language of your choice (Visual C# or Visual Basic). In the Templates pane, choose Windows Application. Choose a name and location for the project and click OK.
Step 2: Drag and drop the PictureBox(picBox) and the TrackBar(zoomSlider) controls on to the form. We will be using the Trackbar control to scroll and configure the zoom value.
Now declare a class level variable of the type Image. Doing this will help us re-apply the transformations (zoom in zoom out) on the original image rather than the already transformed image.
C#
private Image imgOriginal;
VB.NET
Private imgOriginal As Image
In the Form1_Load, set the following properties on the two controls. Here we set the image location using the Image.FromFile. You can also use the Resources class to set images in your application:
C#
private void Form1_Load(object sender, EventArgs e)
{           
    // set image location
    imgOriginal = Image.FromFile(@"C:\New Folder\picture1.jpg");
    picBox.Image = imgOriginal;
 
    // set Picture Box Attributes
    picBox.BackgroundImageLayout = ImageLayout.Stretch;
  
    // set Slider Attributes
    zoomSlider.Minimum = 1;
    zoomSlider.Maximum = 5;
    zoomSlider.SmallChange = 1;
    zoomSlider.LargeChange = 1;
    zoomSlider.UseWaitCursor = false;
 
    // reduce flickering
    this.DoubleBuffered = true;
}
VB.NET
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
      ' set image location
      imgOriginal = Image.FromFile("C:\New Folder\picture1.jpg")
      picBox.Image = imgOriginal
 
      ' set Picture Box Attributes
      picBox.BackgroundImageLayout = ImageLayout.Stretch
 
      ' set Slider Attributes
      zoomSlider.Minimum = 1
      zoomSlider.Maximum = 5
      zoomSlider.SmallChange = 1
      zoomSlider.LargeChange = 1
      zoomSlider.UseWaitCursor = False
 
      ' reduce flickering
      Me.DoubleBuffered = True
End Sub
 
Step 3: Let us now create our zoom functionality.
C#
public Image PictureBoxZoom(Image img, Size size)
{
    Bitmap bm = new Bitmap(img, Convert.ToInt32(img.Width * size.Width), Convert.ToInt32(img.Height * size.Height));
    Graphics grap = Graphics.FromImage(bm);
    grap.InterpolationMode = InterpolationMode.HighQualityBicubic;
    return bm;
}
VB.NET
Public Function PictureBoxZoom(ByVal img As Image, ByVal size As Size) As Image
      Dim bm As Bitmap = New Bitmap(img, Convert.ToInt32(img.Width * size.Width), Convert.ToInt32(img.Height * size.Height))
      Dim grap As Graphics = Graphics.FromImage(bm)
      grap.InterpolationMode = InterpolationMode.HighQualityBicubic
      Return bm
End Function
 
In the code above, we create a new instance of the Bitmap class using the image passed to the function. This image is scaled to the specific size and is taken into a Graphics object where the image is prefiltered using InterpolationMode.HighQualityBicubic to ensure high quality transformed images. The function then returns the transformed image back to the caller.
Step 4: The final step is to register the ‘Scroll’ event of the TrackBar(zoomSlider) control and call the zoom function as shown below:
C#
private void zoomSlider_Scroll(object sender, EventArgs e)
{
    if (zoomSlider.Value > 0)
    {
        picBox.Image = null;
        picBox.Image = PictureBoxZoom(imgOriginal, new Size(zoomSlider.Value, zoomSlider.Value));
    }
}
VB.NET
Private Sub zoomSlider_Scroll(ByVal sender As Object, ByVal e As EventArgs)
      If zoomSlider.Value > 0 Then
            picBox.Image = Nothing
            picBox.Image = PictureBoxZoom(imgOriginal, New Size(zoomSlider.Value, zoomSlider.Value))
      End If
End Sub
That’s it. With a few lines of code, you can emulate zoom functionality in your picturebox and use it in your applications. I hope you liked the article and I thank you for viewing it.

If you liked the article,  Subscribe to my RSS Feed. 
 
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Dmitriy Melnik on Friday, July 24, 2009 2:56 AM
The article helped me a lot. Thanks!
Comment posted by excellent article on Friday, September 11, 2009 4:27 PM
a pleasure to read.
Comment posted by neodean on Saturday, January 16, 2010 1:50 AM
hello man .
This is neodean
it is not working... no effect on while sliding can you please suggest me .

Please soon
Thanks in advance...
Comment posted by Suprotim Agarwal on Sunday, January 17, 2010 2:54 AM
neodean: The code works just fine. Just upload your app to a server where I can download it and i will take a look at it in a couple of days
Comment posted by Taeven on Monday, March 22, 2010 3:42 PM
The code works if you add the handler to the zoomSlider_Scroll method
Comment posted by statlidi on Thursday, April 1, 2010 7:06 AM
Hi,
I tried the code with a "4623x6041" image and I've got "ArgumentException was unhandled" error at the line:
Bitmap bm = new Bitmap(img, Convert.ToInt32(img.Width * size.Width), Convert.ToInt32(img.Height * size.Height));
I think the code cannot handle big sized images...    
Comment posted by SIBR on Friday, April 16, 2010 4:11 AM
Tnx buddy
Its working ....................... :D
Comment posted by ateendra on Thursday, July 22, 2010 3:23 PM
hi, i am trying to implement the same logice in VS 2008 c++ environment, i am not able to identify the Size data type used as function parameter!! please advice how to get it or another way to it!!
Comment posted by denis on Monday, September 27, 2010 7:47 PM
it is not working. somebody says the code works if you add the handler to the zoomslider method but i dont understand this
Comment posted by Sinbad on Thursday, January 27, 2011 8:56 PM
I had my SizeMode property of the Picturebox set to Stretch, didn't work. Changed it to Normal and it behaves as described.
Thanks!
Comment posted by alia on Sunday, November 13, 2011 11:39 PM
Salam, i ve tried you coding its working .. just i have some problem with
grap.InterpolationMode = InterpolationMode.HighQualityBicubic; i got error. thanks again.
Comment posted by alia on Sunday, November 13, 2011 11:39 PM
Salam, i ve tried you coding its working .. just i have some problem with
grap.InterpolationMode = InterpolationMode.HighQualityBicubic; i got error. thanks again.
Comment posted by jsmith on Monday, February 20, 2012 6:44 AM
Add to Form1_Load:
zoomSlider.Scroll += new System.EventHandler(zoomSlider_Scroll);
Comment posted by himanshi on Thursday, March 1, 2012 2:19 AM
its a very good article.... trough ths article i am able to zoom my picture....
Comment posted by pd on Saturday, April 21, 2012 3:42 AM
For all those having error in Interpolation Mode, add the following line at the top anywhere(before the definition of class):

using System.Drawing.Drawing2D
Comment posted by Wowie Em on Friday, June 1, 2012 3:03 AM
for those who said its not working, try these

with:
Private Sub zoomSlider_Scroll(ByVal sender As Object, ByVal e As EventArgs)

change to:
Private Sub zoomSlider_Scroll(ByVal sender As Object, ByVal e As EventArgs) Handles zoomSlider.Scroll

before:
Public Class Form1

add this
Imports System.Drawing.Drawing2D

add me up @ fb
Wowie Em :)
Comment posted by Avanleeuwen on Sunday, June 3, 2012 2:39 PM
You take the image from bitmap bm and write to graphics object grap.  But how are the results returned back to the bitmap bm from the grap object?
Comment posted by traXman on Friday, August 10, 2012 3:30 AM
C# Code does not work (image does not change).

I'm using Visual Studio 2010 Ultimate Edition.
Comment posted by angry on Friday, November 16, 2012 10:59 AM
THIS CRAP DOESNT WORK
Comment posted by Quoctien.tedi on Friday, September 20, 2013 10:21 PM
Hi!
I'm Tiến. I'm from Vietnam! I want to write a Code about solver and drawing a quadratic equation function ( example: y= a*x^2 + b*x +c from x1= - 20 to x2 = 20) on the PictureBox in the VB.net. If solver it on the VB.6 is OK. Now I want to solver it on the VB.net. I'm unable to do it.
   You could help me as soon as possible. Thank you very much
QUOCTIEN
Comment posted by quoctien.tedi on Friday, September 20, 2013 10:23 PM
I'm Tiến. I'm from Vietnam! I want to write a Code about solver and drawing a quadratic equation function ( example: y= a*x^2 + b*x +c from x1= - 20 to x2 = 20) on the PictureBox in the VB.net. If solver it on the VB.6 is OK. Now I want to solver it on the VB.net. I'm unable to do it.
   You could help me as soon as possible.Reply to me via email:quoctien.tedi@gmail.com
Thank you very much
QUOCTIEN

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel