Saturday, August 16, 2008

Image Manipulation using GDI+ - the C# way : Basics

Image manipulation is considered one of the difficult tasks in Graphics Programming. This is more so if the Operating System under consideration is Windows. The reason is that to achieve efficiency nothing can find a better option than Windows API. The APIs provided by Windows comes under the GDI roof. GDI is short for Graphics Device Interface. However, GDI works at low level graphics. So to use it good understanding of how Windows work is required. Even with MFC, GDI is a bit complicated. But with evolution of GDI+ the scenario is changing. The major change between GDI and GDI+ is that GDI exposes only APIs for unmanaged code whereas GDI+ provides for both managed as well as unmanaged code. Hence GDI+ is oriented towards .Net based languages. And in the world of .Net, one of the best options is C#. So in this discussion, I would be focusing on how to use the basic image manipulations using GDI+ library in C#. The first section would focus on the terminology used by GDI+ and image manipulation in general. In the second section I would detail the steps involved in image manipulation using GDI+. The last section would be about using the basic image manipulation within a real world application. That’s the outline for this discussion.

Image Manipulation using GDI+ - the Terminology:

Before understanding how to use GDI+ APIs for image manipulation, it is better to understand what GDI+ really is and what constitutes its vocabulary. If we consider basic image manipulation, there four points that need to be understood which are:

1. GDI+

2. Vector Graphics

3. Raster Graphics

4. Imaging

The second, third and fourth are integral part of image manipulation vocabulary. The fourth term in itself consists of many terms, some which would be discussed in this section.

1. GDI+:

By definition “GDI+ is a library that provides an interface that allows programmers to write Windows and Web graphics applications that interact with graphical devices such as printers, monitors, or files”. In essence, it provides a layer of abstraction over varied devices with which GUI needs to work. This abstraction works by converting the data into device compatible form. The device then turns the data into human readable form. The implementation of GDI+ is in the form of C++ classes that can be used from .Net environment. In .Net library, GDI+ classes are exposed through the System.Drawing and its namespaces.

2. Vector Graphics:

By definition “Graphics in which an image is stored as a series of numbers defining size, position, and shape”. In other words, in Vector graphics the image contains position vectors describing the image, where a vector represents both quantity and direction. For example, instead of containing a bit in a file for say a line being drawn, a vector graphics file describes a series of points to be connected. Also since the file contains vector commands, the size of the file becomes small.

3. Raster Graphics:

Raster is grid of x- and y- co-ordinates on a display space which, in this case is the display device. A Raster Graphics file contains information identifying which of these coordinates to illuminate using monochrome (black and white) or spectro-chrome (color) values. Raster images are also known as Bit-mapped images or Bitmaps because it contains information directly mapped to the display device’s grid. Due to this they have larger size than that of Vector Graphic files.

4. Imaging:

Imaging is the process of viewing and manipulating the images. In managed GDI+, imaging has two facets – Basic and Advanced. The processes in Basic covers loading and saving, zooming, scaling etc. whereas that in Advanced covers color palette, metafiles and tagged images. The basic functionalities are encapsulated in Image class. It provides methods to load, save and create images. The subclasses of Image class i.e. Bitmap and Metafile provides the functionality for displaying and manipulating the images.

That was a bird’s eye view of the recurring terms in the world of GDI+ and image manipulation. In the next section I will discuss about steps in loading and manipulating it using flipping as well as rotating the image.

Image Manipulation Using GDI+ - Step By Step:

Now lets have a look at steps at using the GDI+ for image manipulation. There are four main steps:

1. Overriding the Paint event of Form

2. Obtaining the Graphics object

3. Obtaining the Image object

4. Apply manipulation methods

First two steps is required whenever one has to work with GDI+. However, the last two comes into picture only when image manipulation has to be done. So here are the details:

1. Overriding the Paint event of form:

In .Net applications, drawing is done on a Form’s surface. This is same for both web applications as well as desktop application. The function where the actual drawing code can be hooked into is the Paint method. So, first step is to override this method to get foothold into the draw process within the application. This can be achieved either by supplying Paint handler to the Form’s paint method or by overriding OnPaint method. Though its better to provide Paint handler.

2. Obtaining the Graphics object:

The next step is to obtain the object of Graphics class. Because only through the Graphics object that the drawing methods can be called. To show an image it has to be drawn on to the Form. That can only be done using the DrawImage method of an object of Graphic class. An object of Graphics object is associated with a form. So it can be obtained by-

a. Using PaintEventArgs argument passed into the Paint handler

b. Using PaintArgs argument passed into the OnPaint method

c. Using CreateGraphics method of a Form.

The example of the first method would be thus:

private void form1_Paint(object sender, PaintEventArgs e)

{

Graphics g = e.Graphics;

}

where form1_Paint is the handler for Paint event of Form form1. The Graphics property of the PaintEventArgs returns a Graphics object associated with the Form object. The second way can be exemplified as :

protected override void OnPaint(PaintEventArgs e)

{

Graphics g = e.Graphics;

}

The main difference between first and second is that in the second way, the OnPaint method is overridden. The example for the third way would be :


Graphics g = this.CreateGraphics();

Where this refers to the Form in which this statement has been embedded. The CreateGraphics() method returns a method object of the Form. The only drawback of this approach is that the Graphics object would have to be disposed manually using dispose method of the Graphics object. I prefer the first method. Hence I would be using it henceforth.


3. Obtaining the Image object:

Image object can be obtained in three different ways using the static methods provided by Image class:

a. FromFile method returns an Image from the file specified as argument.


b. FromHbitmap creates and returns an Image object from a window handle to a

bitmap.


c. FromStream creates an Image object from a stream of bytes (in a file or a

database).


Among these, the first method is most commonly used if the image is available as a file, whereas the third method comes handy in web applications where the images would be stored as a column value of a table. The following statements creates an object of Image class using the first method:


Image curImage = Image.FromFile(“flower.bmp”);


4. Apply manipulation methods:

For the sole purpose of imaging, the Image class provides many methods. The most common in imaging are Flip and Rotate. The Image class provides for these by the following method – RotateFlip. The parameter to this method defines whether the flip as well as rotation both has to be done or only one of flip and rotation has to be applied. It also defines through what degrees flip or rotate has to be done. The following table provides most common arguments to the RotateFlip method as well as their description. The argument being passed are the members of RotateFlipType.




Member

Description

Rotate180FlipNone

180-degree rotation without flipping

Rotate180FlipX

180-degree rotation with a horizontal flip

Rotate180FlipXY

180-degree rotation with horizontal and vertical flips

Rotate180FlipY

180-degree rotation with a vertical flip

Rotate270FlipNone

270-degree rotation without flipping

Rotate270FlipX

270-degree rotation with a horizontal flip

Rotate270FlipXY

270-degree rotation with horizontal and vertical flips

Rotate270FlipY

270-degree rotation with a vertical flip

Rotate90FlipNone

90-degree rotation without flipping

Rotate90FlipX

90-degree rotation with a horizontal flip

Rotate90FlipXY

90-degree rotation with horizontal and vertical flips

Rotate90FlipY

90-degree rotation with a vertical flip

RotateNoneFlipNone

No rotation and no flipping

RotateNoneFlipX

No rotation, with a horizontal flip

RotateNoneFlipXY

No rotation, with horizontal and vertical flips

RotateNoneFlipY

No rotation, with a vertical flip


For example to flip and rotate an image through 90 degrees on both X- and Y- axes the statement would be:


curImage.RotateFlip(RotateFlipType.Rotate90FlipXY);


where curImage is an object of the type Image and the argument tells the RotateFlip method that the image has to be rotated through 90 degrees and need to be flipped both vertically and horizontally.


That brings us to the end of this section. In the next section I would develop an application that would load, flip and rotate the loaded image.


Image Manipulation – In the Real World:

Starting from this part onwards, I would be developing an image manipulation application using C# and GDI+. The basic version that would be developed now would provide the following features:


1. Load an image file

2. Rotate the loaded image 90 degrees

3. Flip the image along X- axis


First the menus have to be setup as shown in the figure below.

Fig1 – GDI_1.jpg

Fig2 - GDI_1_RotateFlip.jpg


The names of the menus are:


mnuLoad – the submenu that would show the Open dialog box and loads the file

mnu90rotate – rotates the image by 90 degrees.

mnuXfilp- flips the image along X-axis.


Here is the handler for loading the image:


private void mnuLoad_Click(object sender,

System.EventArgs e)

{

// Create OpenFileDialog

OpenFileDialog opnDlg = new OpenFileDialog();

// Set a filter for images

opnDlg.Filter =

"All Image files|*.bmp;*.gif;*.jpg;*.ico;"+

"*.emf;,*.wmf|Bitmap Files(*.bmp;*.gif;*.jpg;"+

"*.ico)|*.bmp;*.gif;*.jpg;*.ico|"+

"Meta Files(*.emf;*.wmf;*.png)|*.emf;*.wmf;*.png";

opnDlg.Title = "ImageViewer: Open Image File";

opnDlg.ShowHelp = true;

// If OK, selected

if(opnDlg.ShowDialog() == DialogResult.OK)

{

// Read current selected file name

curFileName = opnDlg.FileName;

// Create the Image object using

// Image.FromFile

try

{

curImage = Image.FromFile(curFileName);

}

catch(Exception exp)

{

MessageBox.Show(exp.Message);

}

}

// Repaint the form, which forces the paint

// event handler

Invalidate();

}

The name of the file returned by the open file dialog is set as the current file name. then it is used to load the file using the FromFile function of the Image class. The returned image is assigned to the curImage variable which is of type Image and its scope is of class level. Next Inavlidate() method is called so that paint event is fired. Following the code, embedded in the Form’s Paint method handler, that actually draws the image:


private void Form1_Paint(object sender,

System.Windows.Forms.PaintEventArgs e)

{

Graphics g = e.Graphics;

if(curImage != null)

{

// Draw image using the DrawImage method

g.DrawImage(curImage,

AutoScrollPosition.X,

AutoScrollPosition.Y,

curImage.Width,

curImage.Height );

}

}


The logic checks whether the current image is null or not. If not null, the DrawImage method of Graphic class is given the curImage as the Image to be loaded. The Graphic object is obtained from the Graphics property of PaintEventArgs object. Next the handler for rotating the image – it is embedded in the handler for the mnu90rotate menu item. Here is the code:


// Rotate 90 degrees

private void mnu90rotate_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

curImage.RotateFlip(

RotateFlipType.Rotate90FlipNone);

Invalidate();

}

}


The image is rotated using the RotateFlip method of Image class. Since curImage is of Image class type, hence the method can be directly called on the Image object. Next it calls the Inavlidate() method to redraw the image.


Last comes the flip logic. It is embedded in the handler for the mnuXflip menu item.


// Flip X

private void mnuXflip_Click(object sender,

System.EventArgs e)

{

if(curImage != null)

{

curImage.RotateFlip(

RotateFlipType.RotateNoneFlipX);

Invalidate();

}

}

That’s all for the example. This sets up the stage for image manipulation using GDI+ in C#. However certain aspects of the problem of image manipulation have been left out including saving the image and how GDI+ works. These will be the topics that will be tackled in the next part of this series. Till then…

Note: You can find the article on: http://www.aspfree.com/c/a/C-Sharp/Basic-Image-Manipulation-using-GDI-and-C/

Realms- Securing the J2EE Applications using Container Services

Realms- Securing the J2EE Applications using Container Services

In the world of web applications, security is paramount, more so when the platform is J2EE. A J2EE application consists of different components such as Web Component, Business Logic components and so on. Each of these components execute in their own containers. So, in essence, each component can be provided security by the container in two ways:

  1. Declarative Security

Declarative security is based on Realms, Roles, Users and Groups (more on that later).

  1. Programmatic Security

In Programmatic security, the security is provided through the code embedded in the application itself. Java Authentication and Authorization Services or JAAS belongs to this category.

Securing a web application (for that matter any application) has always two broad phases- Authentication and Authorization. In authentication one validates the credentials of the user. Login procedure is a part of authentication. The next step is setting up and controlling the access rights of the successfully authenticated user. This complete phase comes under Authorization. In authorization a user’s right to access the resources provided by the application is controlled.


In a J2EE application, both of these are managed using Declarative Security. The security service uses the verified credentials supplied at the authentication to control the access to the resources within the application. Hence when authorization comes into picture authentication must also be addressed. Hence here both the phases and the role of Realms in these phases will be discussed here.



  1. Realms, Roles and Users:

Realms, roles and users- these words crop up every time security is discussed in the context of J2EE security. So what are these? Let’s have a detailed view of the trinity of security.


    1. Realms:

A realm defines the boundary of an application. Whatever comes within this boundary is secure. Technically, a realm is a policy that defines how a user is authenticated in a secured domain. This policy contains the list of users and the mechanism to authenticate them. This is similar to Access Control List and authentication mechanism deployed by Windows NT based systems and/or UNIX based systems.


    1. User/Principal:

A Principal is user within the security policy domain. The principal is also known as user within the realm. The username of the user that he/she uses to login and that user’s principal name need not be similar. That’s what the J2EE specification tells but almost all the J2EE implementations utilize the username itself as the principal name.


    1. Roles:

Roles are the references to the actual roles described within the application. The developer uses this reference to map the user to a role. Each user has a role reference mapped into his/her principal name. The reference in turn is mapped onto the actual role within the application. Common role references are Administrator, role1 etc.


  1. Common Implementations of Realms:

As mentioned J2EE application starts using the container’s security services from the time of user’s authentication. Hence the chief implementations of realms also are based on how or where the principals and the related realms are stored. Whenever the container needs to lookup the names and the roles, it uses these ‘storages’. The users and their roles can be stored in three major ways which are xml files, relational databases and directory of LDAP based directory server. So the implementations are:


    1. Memory Realm

    2. JDBC Realm

    3. JNDI Realm

  1. Memory Realm:

Memory realm is based on xml files. All the user names, passwords and their respective roles are stored in a xml file. Whenever the container starts up, it parses this xml file and loads the information into the memory. So until the server is stopped, the complete information is stored within the memory space of the container. Whenever authentication and successive authorization has to be done the supplied credentials (from here I will be using the term credentials for the information supplied by the user) are checked against the in-memory information. The upside of this implementation is that it is easier to setup and use. The downside is that newer information added to the xml file won’t be reflected till the container is restarted. So it is not a good choice for production purposes.

  1. JDBC Realm:

In JDBC realm, the credentials of a user are stored in a relational database table. The container uses JDBC driver to access the information. The major difference between memory realm and JDBC realm is the way in which the credentials are stored. The JDBC realm, as already said, uses tables. The default (also the commonly used) names of these tables are Users and Roles. Whenever a new user is registered, the application or the web administrator has to enter the credentials into the Users table and the corresponding role has to be entered into the Roles table. The container, whenever required uses the information available in the tables to authenticate as well authorize a particular user. The advantage of this implementation is that new information can be entered and used without restarting the server. Also data becomes more secure as the data is not stored in plain text files. Hence for most of the production purposes it is recommended as well as used.


  1. JNDI Realms:

JNDI Realm uses LDAP services provided by a JNDI provider. This is the most complex and the most extensive container based security implementation that any vendor provides. An LDAP directory server contains credentials of the user. The credentials are kept as directory entries in the server. These entries are accessed via the JNDI services within the container. By default, the authentication is done by Bind mode. In this mode, the realm binds the user to the DN entry of the LDAP server using the username and password provided by the user. A user is said to be authenticated if this simple bind succeeds. The passwords of the registered users are not saved in plain text. Instead digest of these passwords are store. Digesting is a form of encryption. So security fears can be dispelled. Again, as in the case of JDBC realms, the entry of registered users is left to the application or web administrator. Though JDBC and JNDI are almost similar, yet the extensive choices provided by the JNDI realm gives it an upper hand.


  1. Implementation of Realm -An example:

So much for the theory, lets see a real world example. As I have already mentioned, in the Declarative security, the constraints are declared in the deployment descriptor i.e. web.xml. So the only part one has to deal with as a web developer is deployment descriptor.


The example that I am citing here deals with a java based Content Management System (CMS). The CMS (lets call it JCMS) has certain resources such as video files, documents etc that can be accessed only by authorized users only. To be more precise we have secure the folders containing the resources. Let’s see how to do it.


Once all the mappings concerning the web application are done, the security declarations and mappings come into picture. The mapping for securing the application resources comes between the following:

<web-app>

:

:

<security-constraint>

:

:

:

</security-constraint>

:

:

</web-app>

In other words to the security mapping <security-constraint> acts as parent node. Then the resources that have to be secured must be declared. Like servlet mappings it can be done for each resource separately or all the resources can be brought under the same declaration.

<web-app>

:

:

<security-constraint>

<web-resource-collection>

:

:

</web-resource-collection>

</security-constraint>

:

:

</web-app>


The <web-resource-collection> encapsulates the various resources that has to be secured. The next step is to give the name to the resource realm and then provide the url that would be used to access the resources.

<web-app>

:

:

<security-constraint>

<web-resource-collection>

<web-resource-name>Protected Area</web-resource-name>

<!-- Define the context-relative URL(s) to be protected -->

<url-pattern>/secured/resources/*</url-pattern>

:

:

</web-resource-collection>

</security-constraint>

:

:

</web-app>


Then, tell the container, what are the HTTP methods, that would be used to access the resources. If the methods are listed, then only those methods would be protected.

<web-app>

:

:

<security-constraint>

<web-resource-collection>

<web-resource-name>Protected Area</web-resource-name>

<!-- Define the context-relative URL(s) to be protected -->

<url-pattern>/secured/resources/*</url-pattern>

<http-method>DELETE</http-method>

<http-method>GET</http-method>

<http-method>POST</http-method>

<http-method>PUT</http-method>

</web-resource-collection>

:

:

</security-constraint>

:

:

</web-app>


Here we are telling the container that we want to authenticate all DELETE, GET,POST,PUT methods. So whenever any one of these methods are used in request, then container fires up the authentication process. But there are five types of authentication ( Form based and Basic are two of the most commonly used. How to tell the container which one to use? But before that the container needs to be told the authentic users for this resource. This is done a follows:

<web-app>

:

:

<security-constraint>

<web-resource-collection>

<web-resource-name>Protected Area</web-resource-name>

<!-- Define the context-relative URL(s) to be protected -->

<url-pattern>/secured/resources/*</url-pattern>

<http-method>DELETE</http-method>

<http-method>GET</http-method>

<http-method>POST</http-method>

<http-method>PUT</http-method>

</web-resource-collection>

<auth-constraint>

<!-- Anyone with one of the listed roles may access this area -->

<role-name>raj</role-name>

<role-name>admin</role-name>

</auth-constraint>

</security-constraint>

:

:

</web-app>


Once the user list is given, then the part comes where the type of authentication has to be provided.

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>Protected Area</web-resource-name>

<!-- Define the context-relative URL(s) to be protected -->

<url-pattern>/secured/resources/*</url-pattern>

<http-method>DELETE</http-method>

<http-method>GET</http-method>

<http-method>POST</http-method>

<http-method>PUT</http-method>

</web-resource-collection>

<auth-constraint>

<!-- Anyone with one of the listed roles may access this area -->

<role-name>raj</role-name>

<role-name>admin</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>Example Basic Authentication Area</realm-name>

</login-config>


:

:

</web-app>



The <login-config> is the place where the type of authentication and the realm to be authenticated. Here we are using BASIC authentication that means whenever anyone tries to access the secured resources the container pops up the standard window dialog demanding the user name and password.


So we have secured our application without even writing a line of java code. Easy… isn’t it?


Where should one go from here? The next logical step is making the application more secure by using JAAS. How to do it … it’s for another time.