Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » WPF » Image Viewer in WPF

Image Viewer in WPF

ImageViewer is an open source project written in WPF and C# that allows users to view images and manipulate them.

Author Rank :
Page Views : 31899
Downloads : 1199
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WPF ImageViewer.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Image Viewer

The ImageViewer project is an open source project written using WPF, XAML, and C#. This project allows users to view and manipulate imates including extensions .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff. The application looks like following and supports viewing and rotation at this time. I am adding more features to this project and will be uploading new features soon. If you plan to work on this project, let me know and we can share the functionality.


Latest Updates: Feb 07, 2010

  • Project updated to Visual Studio 2010
  • Cleaned up UI
  • Added Rotate feature

Features currently I am working on:

  • Image Transformation - Skew, Scale, Translate
  • GrayScale
  • Zoom In/Zoom Out
Need Help On:
  • Cool Toolbar buttons
  • Cool menu options
  • Bitmap effects


ImageViewer.jpg


The Image Class

The Image class is used to load and view an image in WPF. This class displays .bmp, .gif, .ico, .jpg, .png, .wdp, and .tiff files. If a file is a multiframe image, only the first frame is displayed. The frame animation is not supported by this class.

 

The Source property of Image class is the file an image displays. The Source property is a BitmapImage, which can be converted using the following code:

 

ImageViewer1.Source = new BitmapImage(new Uri("Creek.jpg", UriKind.Relative));

 

In the above code snippet, UriKind let you set if the image is relative to the application path or has an absolute path.

 

I create a WPF application with two labels, a button, and an Image control. The XAML code looks like following:

 

<Window x:Class="WPFImageViewer.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="409" Width="574">

    <Grid >

        <Label Content="Label" Height="32" HorizontalAlignment="Left" Margin="11,10,0,0"

               Name="FileNameLabel" VerticalAlignment="Top" Width="393"

               Background="LightGray" BorderBrush="Gray" BorderThickness="1"/>

        <Button Content="Browse a File" Height="34" HorizontalAlignment="Left" Margin="410,8,0,0"

                Name="BrowseButton" VerticalAlignment="Top" Width="119"

                Foreground="Maroon" FontSize="16" FontFamily="Georgia" Click="BrowseButton_Click" />

        <Image Height="305" HorizontalAlignment="Left" Margin="14,53,0,0"

               Name="ImageControl" Stretch="Fill" VerticalAlignment="Top" Width="390" />

        <Button Content="Rotate" FontFamily="Georgia" FontSize="12" Foreground="Maroon"

                Height="26" HorizontalAlignment="Left" Margin="410,61,0,0"

                Name="RotateButton" VerticalAlignment="Top" Width="56" Click="RotateButton_Click" />

        <ComboBox Height="30" HorizontalAlignment="Right" Margin="0,57,12,0" Name="RotationList"

                  VerticalAlignment="Top" Width="68" SelectedIndex="0" SelectionChanged="RotationList_SelectionChanged">

            <ComboBoxItem Content="Rotate0" ContentStringFormat="Rotate0" />

            <ComboBoxItem Content="Rotate90" ContentStringFormat="Rotate90" />

            <ComboBoxItem Content="Rotate180" ContentStringFormat="Rotate180" />

            <ComboBoxItem Content="Rotate270" ContentStringFormat="Rotate270" />

        </ComboBox>

    </Grid>

</Window>

 

 

The Browse button click event handler looks like following:

 

private void BrowseButton_Click(object sender, RoutedEventArgs e)

{

    OpenFileDialog dlg = new OpenFileDialog();

    dlg.InitialDirectory = "c:\\";

    dlg.Filter = "Image files (*.jpg)|*.jpg|All Files (*.*)|*.*";

    dlg.RestoreDirectory = true;

 

    if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    {

        string selectedFileName = dlg.FileName;

        FileNameLabel.Content = selectedFileName;

        BitmapImage bitmap = new BitmapImage();

        bitmap.BeginInit();

        bitmap.UriSource = new Uri(selectedFileName);

        bitmap.EndInit();

        ImageViewer1.Source = bitmap;

    }

}

Click on the Browse button let you browse the files and selected file is displayed in the Viewer.


The Rotate button rotates an image based on the rotate drop down selection. It has Rotate0, Rotate90, Rotate180, and Rotate270 options.

The Rotate button click event handler code is listed below.


private void RotateButton_Click(object sender, RoutedEventArgs e)

{

    if (selectedFileName.Length > 0)

    {

        BitmapImage bitmap = new BitmapImage();

        bitmap.BeginInit();

        bitmap.UriSource = new Uri(selectedFileName);

        bitmap.Rotation = (Rotation)Enum.Parse(typeof(Rotation),

            RotationList.SelectionBoxItemStringFormat);  

        bitmap.EndInit();

        ImageControl.Source = bitmap;

    }

}


Summary

This article showed how to use the Image control of WPF to load and view the image files. I will be working with this Image Viewer for a while and will build a full-fledged image viewer.

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
wish list by Henri On March 8, 2009
Hi Mahesh, I'd like to be able to zoom in on details in the image, and of course this entails scrolling. Henri
Reply | Email | Modify 
Re: wish list by Mahesh On April 3, 2009

Thanks. I will look into it and see if I can update the project.

Reply | Email | Modify 
zoom in/out by venki On July 21, 2009
hi mahesh,

i need to zoom in/out the pictures and rotate at 360 degree pls help me on this..
Reply | Email | Modify 
small question by lau On November 17, 2009
hey, i have downloaded the zip file, i want to ask why i use the code to my homework
it said the system.window.forms wrong
Reply | Email | Modify 
small question by lau On November 17, 2009
hey, i have downloaded the zip file, i want to ask why i use the code to my homework
it said the system.window.forms wrong
Reply | Email | Modify 
Re: small question by Mahesh On November 17, 2009

What version of Visual Studio are you using? Make sure you have Visual Studio 2008. If you do not have VS 2008, go to MSDN.com and download Visual Studio 2008 Express which is free and then open and run the project.

Reply | Email | Modify 
Re: small question by Mahesh On November 17, 2009

You need to add reference to Windows.Forms.Dll to your project. By default, this reference is not added in a WPF application.

Right click on Project name in Solution Explorer, select Add Reference and then look for System.Windows.Forms.dll

Reply | Email | Modify 
Open and manipulate pdf files using image viewer? by mitesh On April 23, 2010
Hi Mahesh,
My project demands opening a pdf file and do some manipulations on the pdf files such as rotation, zoom-in,zoom-out. Can I use this image control for the same? If not, what is the best approach for WPF to open and manipulate .tif and .pdf files using a common control?
Reply | Email | Modify 
Question about image load by Christopher On April 30, 2010
Hey thanks for great work. I want to ask how to load an image to the wpf application if it is out of the project but the path i relative to the application. I mean something like this: Bitmap b = new Bitmap(".\\MyFolder\\myImage.jpg); ? Because I always get an error that image is out of the project.
Reply | Email | Modify 
vs2010 source code by Robert On August 3, 2010
You said you added rotation and updated code to vs2010.  I can only find the old code.

Where is the new???

Thank you,
Reply | Email | Modify 
thank you by tony On September 14, 2010
Just wish to thank you for your article, new to wpf xaml and C#, examining your code and commenting each line with its operation, learning by dissection, if your interested can send you a copy when I,m done to see how much I have understood
Reply | Email | Modify 
Re: thank you by Mahesh On September 14, 2010
Thank you Tony. I would love to see your project. Please post it here by adding extension to this article. There is an option at the end of this article where you can add your updated code.

Reply | Email | Modify 
New Zip File by Robert On September 14, 2010
Please post a new zip file with your updated VS2010 code.  Thank you.
Reply | Email | Modify 
Re: New Zip File by Mahesh On September 14, 2010
Thank you.

One of these days, I will start updating my articles to VS 2010. In the mean time, you can copy and paste code and it should work.
Reply | Email | Modify 
Suggestions by Robert On September 14, 2010

I just finished a WPF application that presents me with a listviewbox of thumbnails from which I can select an image and display the metadata for that image and allow the metadata to be edited.  I had wanted to add some basic image manipulation but just don't have the expertise to deal with images.  I wanted to add:
 Rotation - by degree, either plus or minus.  Being able to rotate by 90 degrees is good but many of my family pictures were just a little off, maybe a degree or two
 Cropping
 Make Black&White
 Resize
 Brighten or Lighten the image

There are many posts that show how to do some of these things but NONE of them showed how to do it AND SAVE the image.

I did find that if you wanted to display the image AND edit it or the metadata it contains you had to use code similar to that below:

                Dim result As New List(Of MyImage)()

                '            For Each filename As String In System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures))
                For Each filename As String In System.IO.Directory.GetFiles(opt.pDefImageLocation)

                    Try
                        If Not String.IsNullOrEmpty(filename.ToString()) Then

                            If Path.GetExtension(filename.ToString) = ".jpg" Then

                                Dim bi As New BitmapImage()
                                bi.BeginInit()
                                bi.UriSource = New Uri(filename.ToString())
                                bi.CacheOption = BitmapCacheOption.OnLoad
                                bi.EndInit()

                                result.Add(New MyImage(bi, System.IO.Path.GetFileName(filename)))

                            End If

                        End If

                    Catch

                    End Try

                Next filename

                Me.Cursor = System.Windows.Input.Cursors.Arrow

                Return result


I look forward to seeing your improvements.

Reply | Email | Modify 
New Zip File by Robert On September 14, 2010
I tried copy and paste.  It presented problems.  I am not a c# programmer and couldn't fix them.
Reply | Email | Modify 
Re: New Zip File by Mahesh On November 7, 2010
You need to make sure you have a WPF project. Code will not work in Windows Forms or other project types.
Reply | Email | Modify 
Re: New Zip File by Mahesh On November 7, 2010
You need to make sure you have a WPF project. Code will not work in Windows Forms or other project types.
Reply | Email | Modify 
How can I do rotate 20 degree by suleyman On September 8, 2011
I could not picture 20 degrees rotation. Can you help?
Reply | Email | Modify 
Re: How can I do rotate 20 degree by Mahesh On September 8, 2011
There is no option to rotate 20 degree in GDI+. If you're using WPF, you can any angle.
Reply | Email | Modify 
Re: Re: How can I do rotate 20 degree by suleyman On September 9, 2011
I'm using WPF, how can I do this? In addition to the printer at an angle I know how the plot?
Reply | Email | Modify 
Re: Re: How can I do rotate 20 degree by suleyman On September 10, 2011
How do I make the printer to print from an angle of 20 degrees? Please help me!
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.