Images


As useful as curves and lines are, most modern applications also include the need to load and display professionally produced, prepackaged images. Also, some applications themselves produce images that can be saved to a file for later display. Both kinds of applications are supported by the two kinds of images in .NET: bitmaps and metafiles.

A bitmap is a set of pixels at certain color values stored in a variety of standard raster formats such as Graphics Interchange Format (GIF) (.gif files) and Joint Picture Experts Group (JPEG) (.jpg files), as well as Windows-specific formats such as Windows bitmap (.bmp files) and Windows icon (.ico files). A metafile is a set of shapes that make up a vector format, such as a GraphicsPath, but can also be loaded from Windows metafile (.wmf) and enhanced Windows metafile (.emf) formats.

Loading and Drawing Images

Bitmaps as well as metafiles can be loaded from files in the file system as well as files embedded as resources. [6] However, you must use the appropriate class. The Bitmap class (from the System.Drawing namespace) handles only raster formats, and the Metafile class (from the System.Drawing.Imaging namespace) handles only vector formats. Both the Bitmap class and the Metafile class derive from a common base class, the Image class. Image objects are what you deal with most of the time, whether it's drawing them into a Graphics object or setting a Form object's Background property.

[6] For details of loading images from resources, see Chapter 10: Resources.

The easiest way to load the image is to pass a file name to the appropriate class's constructor. After an image has been loaded, it can be drawn using the Graphics.DrawImage method:

 using( Metafile wmf = new Metafile(@"2DARROW3.WMF") ) {   // Draw the full image, unscaled and   // clipped only to the Graphics object   g.DrawImage(wmf, new PointF(0, 0)); } using( Bitmap bmp = new Bitmap(@"Soap Bubbles.bmp") ) {   g.DrawImage(bmp, new PointF(100, 100)); } using( Bitmap ico = new Bitmap(@"POINT10.ICO") ) {   g.DrawImage(ico, new PointF(200, 200)); } 

Drawing an image using a point will cause the image to be rendered at its native size and clipped only by the Graphics object. You can be explicit about this desire by calling DrawImageUnscaled, but it acts no differently than passing only a point to DrawImage.

Scaling, Clipping, Panning, and Skewing

Drawing an image unscaled, although useful, is somewhat boring. Often, you'd like to perform operations on the image as it's drawn to achieve effects. For example, to scale an image as it's drawn to fit into a rectangle, you pass a rectangle instead of a point to DrawImage:

 // Scale the image to the rectangle Rectangle destRect = ...; g.DrawImage(bmp, destRect); 

Going the other way, if you'd like to clip an image but leave it unscaled, you can use the DrawImage method, which takes both a source and a destination rectangle of the same size (Figure 4.23 shows the difference):

 // Clip the image to the destination rectangle Rectangle srcRect = ...; Rectangle destRect = srcRect; g.DrawImage(bmp, destRect, srcRect, g.PageUnit); 
Figure 4.23. Scaling an Image Versus Clipping an Image

The code that does the clipping specifies a source rectangle to take from the image and a destination rectangle on the graphics object. Because both rectangles were the same size, there was no scaling, but this technique allows any chunk of the image to be drawn (and scaled) to any rectangle on the graphics object. This technique also allows for panning . You simply take a chunk out of the rectangle that's not at the upper left (as shown in Figure 4.24):

 Bitmap bmp = new Bitmap(@"C:\WINDOWS\Soap Bubbles.bmp"); Size offset = new Size(0, 0); // Adjusted by buttons void panel1_Paint(object sender, PaintEventArgs e) {   Graphics g = e.Graphics;  Rectangle destRect = this.panel1.ClientRectangle;   Rectangle srcRect =   new Rectangle(   offset.Width, offset.Height, destRect.Width, destRect.Height);   g.DrawImage(bmp, destRect, srcRect, g.PageUnit);  } 
Figure 4.24. A Form That Pans an Image in Four Directions

Not only can you scale an image (or part of an image) to a rectangle, but you can also scale an image (or part of an image) to an arbitrary parallelogram. Several of the DrawImages overloads take an array of three PointF objects that describe three points on a parallelogram, which in turn acts as the destination (the fourth point is extrapolated to make sure that it's a real parallelogram). Scaling to a nonrectangular parallelogram is called skewing because of the skewed look of the results. For example, here's a way to skew an entire image (as shown in Figure 4.25):

 Bitmap bmp = new Bitmap(@"C:\WINDOWS\Soap Bubbles.bmp"); Size offset = new Size(0, 0); // Adjusted by buttons void panel1_Paint(object sender, PaintEventArgs e) {   Graphics g = e.Graphics;  Rectangle rect = this.panel1.ClientRectangle;   Point[] points = new Point[3];   points[0] =   new Point(rect.Left + offset.Width, rect.Top + offset.Height);   points[1] = new Point(rect.Right, rect.Top + offset.Height);   points[2] = new Point(rect.Left, rect.Bottom - offset.Height);   g.DrawImage(bmp, points);  } 
Figure 4.25. An Example of Skewing an Image

Rotating and Flipping

Two other kinds of transformation that you can apply to an image are rotating and flipping. Rotating an image allows it to be turned in increments of 90 degrees ”that is, 90, 180, or 270. Flipping an image allows an image to be flipped along either the X or the Y axis. You can perform these two transforms together using the values from the RotateFlipType enumeration, as shown in Figure 4.26.

Figure 4.26. The Rotating and Flipping Types from the RotateFlipType Enumeration

Notice in Figure 4.26 that the RotateNoneFlipNone type is the original image. All the others are rotated or flipped or both. To rotate only, you pick a type that includes FlipNone. To flip only, you pick a type that includes RotateNone. The values from the RotateFlipType enumeration affect an image itself using the RotateFlip method:

 // Rotate 90 degrees bitmap1.RotateFlip(RotateFlipType.Rotate90FlipNone); // Flip along the X axis bitmap2.RotateFlip(RotateFlipType.RotateNoneFlipX); 

The effects of rotation and flipping are cumulative. For example, rotating an image 90 degrees twice will rotate it a total of 180 degrees.

Recoloring

Rotating and flipping aren't merely effects applied when drawing; rather, these operations affect the contents of the image. You can also transform the contents using an ImageAttributes object that contains information about what kind of transformations to make. For example, one of the things you can do with an ImageAttributes class is to map colors:

 void panel2_Paint(object sender, PaintEventArgs e) {   Graphics g = e.Graphics;   using( Bitmap bmp = new Bitmap(@"INTL_NO.BMP") ) {  // Set the image attribute's color mappings   ColorMap[] colorMap = new ColorMap[1];   colorMap[0] = new ColorMap();   colorMap[0].OldColor = Color.Lime;   colorMap[0].NewColor = Color.White;   ImageAttributes attr = new ImageAttributes();   attr.SetRemapTable(colorMap);  // Draw using the color map     Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);     rect.Offset(...); // Center the image  g.DrawImage   (bmp, rect, 0, 0, rect.Width, rect.Height, g.PageUnit, attr);  } } 

This code first sets up an array of ColorMap objects, each of which contains the old color to transform from and the new color to transform to. The color map is passed to a new ImageAttribute class via the SetRemapTable. The ImageAttribute object is then passed to the DrawImage function, which does the color mapping as the image is drawn. Figure 4.27 shows an example.

Figure 4.27. An Example of Mapping Color.Lime to Color.White

Notice that in addition to mapping the colors, the sample code uses the Width and Height properties of the Bitmap class. The Bitmap class, as well as the Image base class and the Metafile class, provides a great deal of information about the image.

Another useful piece of information is the color information at each pixel. For example, instead of hard-coding lime as the color, we could use the pixel information of the bitmap itself to pick the color to replace:

 ColorMap[] colorMap = new ColorMap[1]; colorMap[0] = new ColorMap();  colorMap[0].OldColor = bmp.GetPixel(0, bmp.Height - 1);  colorMap[0].NewColor = Color.White; 

In this case, we're mapping whatever color is at the bottom left as the pixel to replace. In addition to replacing colors, the ImageAttributes object can contain information about remapping palettes, setting gamma correction values, mapping color to grayscale, and other color- related options as well as the wrap mode (as with brushes).

Transparency

Of course, simply mapping to white or any other color isn't useful if the image needs to be drawn on top of something else that you'd like to show through. For this case, there's a special color called Transparent that allows the mapped color to disappear instead of being replaced with another color:

 ColorMap[] colorMap = new ColorMap[1]; colorMap[0] = new ColorMap(); colorMap[0].OldColor = bmp.GetPixel(0, bmp.Height - 1); colorMap[0].NewColor = Color.Transparent; 

Figure 4.28 shows the effects of using Color.Transparent.

Figure 4.28. Using Color.Transparent in a Color Map

Again, I used the bottom-left pixel as the color to replace, which is the convention used by other parts of .NET. In fact, if you're going to always draw a bitmap with a transparent color and if the color to be made transparent is in the bitmap itself in the bottom-left pixel, you can save yourself the trouble of building a color map and instead use the MakeTransparent method:

 // Make the bottom-left pixel the transparent color bmp.MakeTransparent(); g.DrawImage(bmp, rect); 

If the pixel you'd like to use as the transparency color isn't in the bottom left of the bitmap, you can also use the MakeTransparent overload, which takes a color as an argument. Calling MakeTransparent actually replaces the pixels of the transparency color with the Color.Transparent value. Some raster formats, such as the GIF and Windows icon formats, allow you to specify a transparency color value as one of their legal values. However, even if the raster format itself doesn't support a transparency color, all Bitmap objects, regardless of the raster format, support the MakeTransparent method.

Animation

Just as some raster formats support transparency as a native color, some also support animation. One in particular is the GIF format. The way that images expose support for animation is by supporting more than one image in a single file. GIFs support animation by supporting more than one image in a time dimension, but other formats (such as TIFF files) can support different resolutions or multiple images as pages. You can count how many pages are in each "dimension" by calling the GetFrameCount method with FrameDimension objects exposed by properties from the FrameDimension class:

 // Will throw exceptions if image format doesn't support // multiple images along requested dimension int timeFrames = gif.GetFrameCount(FrameDimension.Time); int pageFrames = gif.GetFrameCount(FrameDimension.Page); int resolutionFrames = gif.GetFrameCount(FrameDimension.Resolution); 

To select which frame to be displayed when the image is drawn is merely a matter of selecting the "active" frame along a dimension:

 int frame = 4; // Needs to be between 0 and frame count -1 gif.SelectActiveFrame(FrameDimension.Time, frame); g.DrawImage(gif, this.ClientRectangle); 

In addition to the multiple frames , the GIF format encodes timing information for each frame. However, that's where things get tricky. Because different image formats support different information, the Image class exposes "extra" information via its GetPropertyItem method. The GetPropertyItem method takes a numeric ID and returns a generic PropertyItem object. The IDs themselves are defined only in a GDI+ header file and the PropertyItem object's Value property. The Value property exposes the actual data as an array of bytes that needs to be interpreted, making usage from .NET difficult. For example, here's how to get the timings for a GIF file:

 // Get bytes describing each frame's time delay int PropertyTagFrameDelay = 0x5100; // From GdiPlusImaging.h PropertyItem prop = gif.GetPropertyItem(PropertyTagFrameDelay);  byte[] bytes = prop.Value;  // Convert bytes into an array of time delays int frames = gif.GetFrameCount(FrameDimension.Time); int[] delays = new int[frames]; for( int frame = 0; frame != frames; ++frame ) {   // Convert each 4-byte chunk into an integer   delays[frame] = BitConverter.ToInt32(bytes, frame * 4); } 

After you have the time delays, you can start a timer and use the SelectActiveFrame method to do the animation. If you do it that way, make sure to convert the delays to milliseconds (1/1000ths of a second), which is what .NET timers like, from centiseconds (1/100ths of a second), which is what GIF time delays are specified in. Or just use the ImageAnimator helper class, which can do all this for you:

 // Load animated GIF Bitmap gif = new Bitmap(@"C:\SAMPLE_ANIMATION_COPY.GIF"); void AnimationForm_Load(object sender, EventArgs e) {  // Check whether image supports animation   if( ImageAnimator.CanAnimate(gif) ) {   // Subscribe to event indicating the next frame should be shown   ImageAnimator.Animate(gif, new EventHandler(gif_FrameChanged));   }  }  void gif_FrameChanged(object sender, EventArgs e) {  if( this.InvokeRequired ) {     // Transition from worker thread to UI thread     this.BeginInvoke(       new EventHandler(gif_FrameChanged),       new object[] { sender, e });   }   else {  // Trigger Paint event to draw next frame   this.Invalidate();  }  }  void AnimationForm_Paint(object sender, PaintEventArgs e) {  // Update image's active frame   ImageAnimator.UpdateFrames(gif);  // Draw image's current frame   Graphics g = e.Graphics;   g.DrawImage(gif, this.ClientRectangle); } 

The ImageAnimator knows how to pull the timing information out of an image and call you back when it's time to show a new one, and that is what calling ImageAnimator.Animate does. When the event is fired , invalidating the rectangle being used to draw the animated GIF triggers the Paint event. The Paint event sets the next active frame using the ImageAnimator.UpdateFrames method and draws the active frame. Figures 4.29, 4.30, and 4.31 show an image being animated.

Figure 4.29. Sample Animation, First Frame

Figure 4.30. Sample Animation, Middle Frame

Figure 4.31. Sample Animation, Last Frame

The only thing that's a bit tricky is that the animated event is called back on a worker thread, not on the main UI thread. Because it's not legal to make any method calls on UI objects, such as the form, from a thread other than the creator thread, we used the BeginInvoke method to transition back from the worker thread to the UI thread to make the call. This technique is discussed in gory detail in Chapter 14: Multithreaded User Interfaces.

Drawing to Images

Certain kinds of applications need to create images on-the-fly , often requiring the capability to save them to a file. The key is to create an image with the appropriate starting parameters, which for a Bitmap means the height, width, and pixel depth. The image is then used as the "backing store" of a Graphics object. If you're interested in getting the pixel depth from the screen itself, you can use a Graphics object when creating a Bitmap:

 // Get current Graphics object for display Graphics displayGraphics = this.CreateGraphics(); // Create Bitmap to draw into based on existing Graphics object Image image = new Bitmap(rect.Width, rect.Height, displayGraphics); 

After you have an image, you can use the Graphics FromImage method to wrap a Graphics object around it:

 Graphics imageGraphics = Graphics.FromImage(image); 

After you've got a Graphics object, you can draw on it as you would normally. One thing to watch out for, however, is that a Bitmap starts with all pixels set to the Transparent color. That may well be exactly what you want, but if it's not, then a quick FillRectangle across the entire area of the Bitmap will set things right.

After you've done the drawing on the Graphics object that represents the image, you can draw that image to the screen or a printer, or you can save it to a file, using the Save method of the Image class:

 image.Save(@"c:\image.png"); 

Unless otherwise specified, the file is saved in PNG format, regardless of the extension on the file name. If you prefer to save it in another format, you can pass an instance of the ImageFormat class as an argument to the Save method. You create an instance of the ImageFormat class using the GUID (Globally Unique ID) of the format, but the ImageFormat class comes with several properties prebuilt for supported formats:

 sealed class ImageFormat {   // Constructors   public ImageFormat(Guid guid);   // Properties   public Guid Guid { get; }  public static ImageFormat Bmp { get; }   public static ImageFormat Emf { get; }   public static ImageFormat Exif { get; }   public static ImageFormat Gif { get; }   public static ImageFormat Icon { get; }   public static ImageFormat Jpeg { get; }   public static ImageFormat MemoryBmp { get; }   public static ImageFormat Png { get; }   public static ImageFormat Tiff { get; }   public static ImageFormat Wmf { get; }  } 

As an example of creating images on-the-fly and saving them to a file, the following code builds the bitmap shown in Figure 4.32:

 void saveButton_Click(object sender, EventArgs e) {   Rectangle rect = new Rectangle(0, 0, 100, 100);  // Get current graphics object for display   using( Graphics displayGraphics = this.CreateGraphics() )   // Create bitmap to draw into based on existing Graphics object   using( Image image =   new Bitmap(rect.Width, rect.Height, displayGraphics) )   // Wrap Graphics object around image to draw into   using( Graphics imageGraphics = Graphics.FromImage(image) ) {  imageGraphics.FillRectangle(Brushes.Black, rect);     StringFormat format = new StringFormat();     format.Alignment = StringAlignment.Center;     format.LineAlignment = StringAlignment.Center;     imageGraphics.DrawString("Drawing to an image", ...);  // Save created image to a file   image.Save(@"c:\temp\image.png");  } } 
Figure 4.32. Example of Drawing to an Image

Icons

Before I wrap up the images section, I want to mention two kinds of images for which .NET provides special care: icons and cursors . You can load a Windows icon (.ico) file into a Bitmap object, as with any of the other raster formats, but you can also load it into an Icon object. The Icon class is largely a direct wrapper class around the Win32 HICON type and is provided mainly for interoperability. Unlike the Bitmap or Metafile classes, the Icon class doesn't derive from the base Image class:

 sealed class Icon :   MarshalByRefObject, ISerializable, ICloneable, IDisposable {   // Constructors   public Icon(string fileName);   public Icon(Icon original, Size size);   public Icon(Icon original, int width, int height);   public Icon(Stream stream);   public Icon(Stream stream, int width, int height);   public Icon(Type type, string resource);   // Properties   public IntPtr Handle { get; }   public int Height { get; }   public Size Size { get; }   public int Width { get; }   // Methods   public static Icon FromHandle(IntPtr handle);   public void Save(Stream outputStream);   public Bitmap ToBitmap(); } 

When setting the Icon property of a Form, for example, you'll use the Icon class, not the Bitmap class. Icons support construction from files and resources as well as from raw streams (if you want to create an icon from data in memory) and expose their Height and Width. For interoperability with Win32, Icons also support the Handle property and the FromHandle method. If you've got an Icon and you'd like to treat it as a Bitmap, you can call the ToBitmap method and the data will be copied to a new Bitmap object. After you've loaded an icon, you can draw it to a Graphics object using the DrawIcon or DrawIconUnstretched method:

 Icon ico = new Icon("POINT10.ICO"); g.DrawIcon(ico, this.ClientRectangle); // Stretch g.DrawIconUnstretched(ico, this.ClientRectangle); // Don't stretch 

Several icons used by the system come prepackaged for you as properties of the SystemIcons class for your own use, as shown in Figure 4.33.

Figure 4.33. Icon Properties from the SystemIcons Class as Shown under Windows XP

Cursors

The other Win32 graphics type that WinForms provides for is the Cursor type, which, like Icon, doesn't derive from the Image base class:

 sealed class Cursor : IDisposable, ISerializable {   // Constructors   public Cursor(string fileName);   public Cursor(IntPtr handle);   public Cursor(Stream stream);   public Cursor(Type type, string resource);   // Properties   public static Rectangle Clip { get; set; }   public static Cursor Current { get; set; }   public IntPtr Handle { get; }   public static Point Position { get; set; }   public Size Size { get; }   // Methods   public IntPtr CopyHandle();   public void Draw(Graphics g, Rectangle targetRect);   public void DrawStretched(Graphics g, Rectangle targetRect);   public static void Hide();   public static void Show(); } 

A Cursor is a graphic that represents the position of the mouse on the screen. It can take on several values based on the needs of the window currently under the cursor. For example, by default, the cursor is an arrow to indicate that it should be used to point. However, when the cursor passes over a text editing window, it often turns into an I-beam to provide for better positioning between characters .

A cursor can be loaded from a file (*.cur) or from one of the system-provided cursors in the Cursors class, as shown in Figure 4.34.

Figure 4.34. System Cursors from the Cursors Class

You can draw a cursor manually using the Draw or DrawStretched method of the Cursor class, but most of the time, you draw a cursor by setting it as the current cursor using the static Current property of the Cursor class. Setting the current cursor will remain in effect only during the current event handler and only when the cursor is over windows of that application. Changing the cursor won't stop another window in another application from changing it to something it finds appropriate. For example, the following changes the application's cursor to the WaitCursor during a long operation:

 void Form1_Click(object sender, EventArgs e) {   try {  // Change the cursor to indicate that we're waiting   Cursor.Current = Cursors.WaitCursor;  // Do something that takes a long time     ...   }   finally {  // Restore current cursor   Cursor.Current = this.Cursor;  } }  // Cursor restored after this event handler anyway...  

Notice the use of the form's Cursor property to restore the current cursor after the long operation completes. Every form and every control has a Cursor property. This cursor becomes the default when the mouse passes over the window. For example, the following code sets a form's default cursor to the Cross:

 void InitializeComponent() {   ...  this.Cursor = System.Windows.Forms.Cursors.Cross;  ... } 

Notice the use of InitializeComponent to set the Form's cursor, indicating that this is yet another property that can be set in the Property Browser, which shows a drop-down list of all the system-provided cursors to choose from.



Windows Forms Programming in C#
Windows Forms Programming in C#
ISBN: 0321116208
EAN: 2147483647
Year: 2003
Pages: 136
Authors: Chris Sells

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net