CrawlTrack: free crawlers and spiders tracking script for webmaster- SEO script -script gratuit de d?tection des robots pour webmaster

 
>>  Visual Studio ã
New Visual Studio 2008 (formerly known as Visual Studio code name "Orcas")


>>   Visual Basic ã
is a tool for productively building type safe and object oriented applications.


GDI+ Image Handling in C#
By Rick Leinecker
August 2, 2007

t was a dream come true when I learned in July 2000 that the .NET framework included image loading, saving, and manipulation. Before that time, you had to either buy a third-party library or write your own code to load and save images. I did both at various times, and each had their fair share of pitfalls.

This article shows you how to use images in your application by calling on the GDI+ classes that provide the needed functionality. It's so easy now that it's hard for me to convince new programmers that in the past, images were difficult to manage.

The Graphics Class

As with all GDI+ methods, we'll draw to a surface (similar to a canvas). The surface can be anything including the physical screen, a printer, or an in-memory bitmap. The Graphics class abstractly represents surfaces so that programmers can forget about the exact surface device. All drawing is done in the same way.

We'll get started learning how to use the Graphics class by creating a simple Windows C# application named LearnImagesClass. Once the application project has been created, we'll go to the form properties, click on the events button (the lightning bolt), and add an OnPaint event handler.

The default method that is created contains a sender object (which I have never used in this context) and a PaintEventArgs object. The wizard-created method is shown below:

private void OnPaint(object sender, PaintEventArgs e)
{

}

One of the members of the PaintEventArgs object is a Graphics object named Graphics. All methods and properties of this Graphics object can be accessed as
e.Graphics.SomeGDIMethodCall(). The following example uses the Graphics object to draw a line:

e.Graphics.DrawLine(new Pen(Color.Black), 0, 0, 250, 250);

The .NET framework supports many image types. But hey, most images on the Internet are Jpegs so we should use that format, right? Not necessarily. Different image types have different characteristics when they're rendered, and we need to discuss several of the most common formats. But first, take a look at the formats that are supported by the .NET framework in the following table.

Name                  Description
Bmp - Bitmap image format (BMP).
Emf - Enhanced Windows metafile image format (EMF).
Exif - Exchangeable Image File (Exif) format.
Gif - Graphics Interchange Format (GIF) image format.
Icon - Windows icon image format.
Jpeg - Joint Photographic Experts Group (JPEG) image format.
MemoryBmp - Memory bitmap image format.
Png - W3C Portable Network Graphics (PNG) image format.
Tiff - Tag Image File Format (TIFF) image format.
Wmf - Windows metafile (WMF) image format.

Picture File Types: GIF, JPG, and PNG

There are three major types of image files that are commonly used on the Internet. While the .NET framework loads and saves ten different formats, the three that are used on the Internet are the ones that most people choose to use for standalone applications.

The three types that we'll talk about are GIF images, JPG images, and PNG images. GIF stands for Graphics Interchange Format. JPG (sometimes JPEG) stands for Joint Photographic Experts Group. PNG stands for Portable Network Graphics. Each of these image file formats offer different advantages and disadvantages; so, what we'll do right now is describe the image file formats and discuss the advantages and disadvantages of each. Deciding which image to use in which setting will be important.

GIF Image Files

The GIF format is a creation of CompuServe, and is used to store multiple bitmap images in a single file for exchange between platforms and systems. Many of these are high-quality images of people, landscapes, cars, and astrophotographs. The vast majority of GIF files contain 16 or 256 color quality images. Grayscale images such as those produced by scanners are also commonly stored using GIF, although monochromographics such as clip art and document images rarely are.

Although the bulk of GIF files are found in the Windows-based environment, GIF is not associated with any particular software application. GIF also is not created for any particular software application need, although most software applications that read and write graphical image data such as paint programs, scanner and video software and most image file display and conversion programs usually support GIF.

The biggest contrast between GIF and JPG is that GIF uses a lossless compression. The compression method used by GIF is LZW. That stands for Lempel, Ziv, and Welch, the three men who invented it. More correctly, Lempel and Ziv created the early version and Welch made modifications later on; but I digress. In any case, the compression method that GIF uses does not degrade the picture quality at all. Every time you save and load the same GIF image, it is recreated with 100 percent integrity. For this reason, if you have an image that must be crisp and clear, and reproduced with the absolute highest quality, GIF would be your choice.

One limitation of GIF in certain circumstances is that it is limited to 256 simultaneous colors. The 256 colors, though, are selected from a palette of millions of colors; but GIF files can only use 256 of those colors at a time. For most Web applications, there's a commonly accepted palette known as the browser-safe palette that many GIF images now use. If you use this browser-safe palette, your GIF images are almost guaranteed to have the best reproduction on systems all over the world. However, if you use some custom palette that is not easy to match on all systems, your image may not look the same and may suffer when it is displayed on another system. One big advantage of GIF files is that one GIF file can store multiple images, and the multiple images can be displayed in sequential order within a browser. These are called animated GIFs, and are very popular on the Web.

JPG Images

JPG refers to a standards organization, a method of file compression, and sometimes a file format. The JPG file interchange format is designed to allow files containing JPG and coded data streams to be exchanged between otherwise incompatible systems and applications. For instance, a Macintosh and an IBM compatible computer can share the same file. JPG files, unlike GIF files, use a compression method that degrades the image at least somewhat. This is called lossy compression: that is, there is a certain amount of loss every time the file is saved. For this reason, if you need an exact replication of the original image, JPG is not necessarily the choice you need to make.

One advantage of JPG, however, is that even with the image degradation you get, for photographic images, you really can't tell much of a difference. It does a great job in images of near photographic quality as opposed to those with crisp, sharp edges.

JPG images are also composed of 24-bit colors. Each pixel in a JPG image can be one of a different color selected from a palette of millions. This is far better than the limitation of 256 colors in a GIF palette. In this case, a JPG image can consist of millions and millions of simultaneous colors.

PNG Images

PNG is lossless as is the GIF format. PNG was developed to overcome the limitations of the GIF format. The first limitation it overcomes is the patented LZW compression algorithm that the GIF format uses. The LZW compression algorithm is not used making the PNG image format free of any royalties. It also overcomes the limitation of 256 simultaneous colors by offering up to 48-bit truecolor.

PNG is a good choice when you need crisp images that use more than 256 colors.

The class that encapsulates an image is the Bitmap class. In order to load an image, you must use the Bitmap class's constructor. There are quite a few overrides, but I almost always use the constructor that takes a single argument specifying the file name as follows.

Bitmap objBitmap = new Bitmap("FileName.jpg");

The Bitmap constructor throws a System.ArgumentException exception. I found this strange, though, as it throws this very same exception if the file doesn't exist. I would have thought there would have been other exceptions thrown that cover file I/O issues.

Once you have the image loaded, there are some very useful properties that the Bitmap class has to offer. The ones that I used most often are Width and Height. The following code loads an image and then displays its width and height in a message box.

Bitmap objBitmap = new Bitmap(strFileName);
string strInfo = "Width:" + objBitmap.Width +
    "Height:" + objBitmap.Height;
MessageBox.Show(strInfo);

You can also create a thumbnail version of the image with the Bitmap.GetThumbnailImage method. The following code shows how to load an image and then create a thumbnail that is 50 pixels wide by 50 pixels high.

Bitmap objBitmap = new Bitmap(strFileName);
Bitmap objThumbnailBitmap = objBitmap.GetThumbnailImage(50, 50,
  null, null);

In the LearnImagesClass demo application, there are three images that are included in the project's debug directory. They are loaded in response to a change in the combo box that contains the image choices. The following code is a simplification of the actual code, but clearly shows how to load an image based on a user's selection.

m_objBitmap = new Bitmap(cmbImageList.SelectedItem + ".jpg");
Invalidate();
Update();

Displaying Images

Displaying images to the drawing surface is easy. It's simply a matter of using the Graphics.DrawImage override that's appropriate. The simplest override (which I use most often) has three arguments: the Bitmap object, the x coordinate, and the y coordinate. The following example shows how it can be used.

private void OnPaint(object sender, PaintEventArgs e)
{
    // m_objBitmap is a Bitmap object that has
    //   has already loaded the image file.
    e.Graphics.DrawBitmap(m_objBitmap, 0, 0);
}

Note that a Graphics object is necessary to render a Bitmap object to any canvas. The OnPaint method is fired in response to a system message (WM_PAINT if you remember your early windows messages). You can get a Graphics object from the application at any time, though, and draw an image without having to cause a window redraw as follows.

Graphics g = Graphics.FromHwnd(this.Handle);
// m_objBitmap is a Bitmap object that has
//   has already loaded the image file.
e.Graphics.DrawBitmap(m_objBitmap, 0, 0);

Scaling an image to the client area is easy. All you need to do is add two more arguments indicating the width and height of the area to which you want to draw. The following example shows how to draw to an area that's 400 pixels wide and 300 pixels high.

e.Graphics.DrawBitmap(m_objBitmap, 0, 0, 400, 300);

The demonstration application provides the option of scaling the loaded image or drawing it unscaled. The following code is a simplified version of what's in the application.

// Visual Studio created this method. It's
//   fired when the window needs to be repainted.
private void OnPaint(object sender, PaintEventArgs e)
{

     // Draw the image in the application
     //  client area.
     if (!chkScale.Checked)
     {
          // Draw the image unscaled.
          e.Graphics.DrawImage(m_objBitmap,
               0, 0);
     }
     else
     {
          // Draw the image scaled.
          e.Graphics.DrawImage(m_objBitmap,
               0, 0,
               ClientRectangle.Width, ClientRectangle.Height);
     }
}

The following two figures show the application rendering an image unscaled, and then scaled.

Creating And Drawing To Images

You can create a blank image very easily. This is handy when you have a set of complex drawing commands that take awhile to execute. Creating a Bitmap object, drawing the complex commands into it, and then rendering the Bitmap object instead of the set of complex drawing commands will make your application perform much better.

To create a blank bitmap, simple use the Bitmap constructor and specify the desired width and height as follows.

Bitmap objBitmap = new Bitmap(400, 300);

The newly-created bitmap is now ready to act as a canvas, but first you need a Graphics object. The Graphics.FromImage method is used to get a Graphics object from a bitmap as follows.

Graphics g = Graphics.FromImage(objBitmap);

The demonstration application draws to an in-memory bitmap. If the user clicks on the Create button, the application creates a new blank bitmap, draws a white rectangle into it, and takes any text in the text box and draws that into the bitmap. The following code is a helper method that performs the steps.

// This helper method creates a custom bitmap object,
//   makes it white, and then draws text from the
//   the text box into it.
void CreateCustomBitmap()
{
     // Create the custom bitmap based on the app client rectangle.
     m_objCustomBitmap = new Bitmap(ClientRectangle.Width,
        ClientRectangle.Height);
     // Get a graphics object from the bitmap.
     Graphics g = Graphics.FromImage(m_objCustomBitmap);
     // Fill the bitmap with a white rectangle.
     g.FillRectangle(new SolidBrush(Color.White), 0, 0,
          m_objCustomBitmap.Width, m_objCustomBitmap.Height);
     // Draw the text string into the bitmap.
     g.DrawString(txtCustomText.Text, new Font("Times New Roman", 35,
       FontStyle.Regular), new SolidBrush(Color.Black),
       new RectangleF(0, 0, ClientRectangle.Width,
       ClientRectangle.Height));
}

Saving Images

Saving images is as easy as the other things we've talked about. The Bitmap.Save method lets you specify the destination filename and the file format as follows.

objBitmap.Save("MyFile.jpg", ImageFormat.Jpg);

One note, though, is that in order to use the ImageFormat enumeration you must add the following statement to the top of your code.

using System.Drawing.Imaging;

The demonstration application has a Save button that allows you to save the current image. The method from the application is shown here.

// Visual Studio created this method. It's
//   fired when the Save button is clicked.
private void btnSave_Click(object sender, EventArgs e)
{
     // If user selects the OK button, then we do stuff.
     if(saveFileDialog1.ShowDialog() == DialogResult.OK)
     {
          // First we set the image format with which we'll save.
          ImageFormat SelectedFormat = ImageFormat.Gif;
          if( rbtnJpg.Checked )
          {
               SelectedFormat = ImageFormat.Jpeg;
          }
          else if( rbtnPng.Checked )
          {
               SelectedFormat = ImageFormat.Png;
          }
          // Now save the image.
          m_objBitmap.Save(saveFileDialog1.FileName, SelectedFormat);
     }
}

Conclusion
Using images in your applications are is easy. And it can really enhance their appearance tremendously.

Source: http://www.devsource.com
Home           Info              More Info        Languages1 Languages2    Techniques1     Techniques2
Ò 2006-2008 www.Visual-Que.com. All rights reserved.