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:

 
 Dim wmf As Metafile = New Metafile("2DARROW3.WMF") g.DrawImage(wmf, New PointF(0,0)) wmf.Dispose() Dim bmp As Bitmap = New Bitmap("Soap Bubbles.bmp") g.DrawImage(bmp, New PointF(100,100)) bmp.Dipose() Dim ico As Bitmap = New Bitmap("POINT10.ICO") g.DrawImage(ico, New PointF(200,200)) ico.Dispose() 

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 Dim destRect As Rectangle = ... 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 Dim srcRect As Rectangle = ... Dim destRect As Rectangle = 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):

 
 Dim bmp As Bitmap = New Bitmap("C:\Windows\Soap Bubbles.bmp") Dim offset As Size = New Size(0,0) ' Adjusted by buttons Sub panel1_Paint(sender As Object, e As PaintEventArgs)   Dim g As Graphics = e.Graphics   Dim destRect As Rectangle = Me.panel1.ClientRectangle   Dim srcRect As Rectangle = New Rectangle(offset.Width, _       offset.Height,destRect.width, destRect.height)   g.DrawImage(bmp, destRect, srcRect, g.PageUnit) End Sub 
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):

 
 Dim bmp As Bitmap = New Bitmap("C:\Windows\Soap Bubbles.bmp") Dim offset As Size = New Size(0,0) ' Adjusted by buttons Sub panel1_Paint(sender As Object, e As PaintEventArgs)   Dim g As Graphics = e.Graphics   Dim rect As Rectangle = Me.panel1.ClientRectangle   Dim points(3) As Point   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)   g.DrawImage(bmp, destRect, srcRect, g.PageUnit) End Sub 
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 (See Plate 16)

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:

 
 Sub panel2_Paint(sender As Object, e As PaintEventArgs)   Dim g As Graphics = e.Graphics   Dim bmp As Bitmap = New Bitmap("INTL_NO.BMP")   Dim mycolormap(1) As ColorMap   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   Dim rect As Rectangle = New Rectangle(0, 0, bmp.Width, bmp.Height)   rect.Offset(...)   g.DrawImage(bmp, rect, 0, 0, rect.Width, _      rect.Height, g.PageUnit, attr)   bmp.Dispose() End Sub 

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 (See Plate 17)

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:

 
 Dim mycolorMap(0) As ColorMap  mycolorMap(0) = new ColorMap()  mycolorMap(0).OldColor = bmp.GetPixel(0, bmp.Height - 1)  mycolorMap(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:

 
 Dim mycolorMap(0) as ColorMap mycolorMap(0) = New ColorMap() mycolorMap(0).OldColor = bmp.GetPixel(0, bmp.Height  1) mycolorMap(0).NewColor = Color.Transparent 

Figure 4.28 shows the effects of using Color.Transparent.

Figure 4.28. Using Color.Transparent in a Color Map (See Plate 18)

Again, we 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 Dim timeframes As Integer = gif.GetFrameCount(FrameDimension.Time) Dim pageFrames As Integer = gif.GetFrameCount(FrameDimension.Page) Dim resolutionFrames As Integer = 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:

 
 Dim frame As Integer = 4 ' Needs to be between 0 and frame count  1 gif.SelectActiveFrame(FrameDimension.Time, frame) g.DrawImage(gif, Me.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 Dim PropertyTagFrameDelay As Integer = &H1500 Dim prop As PropertyItem = gif.GetPropertyItem(PropertyTagFrameDelay) Dim bytes() as Byte = prop.Value ' Convert bytes into an array of time delays Dim frames As Integer = gif.GetFrameCount(FrameDimension.Time) Dim delays(frame) As Integer Dim frame As Integer For frame = 0 to frames  1   Delays(frame) = BitConverter.ToInt32(bytes, frame * 4) Next 

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 Dim gif As Bitmap = New Bitmap("C:\SAMPLE_ANIMATION_COPY.GIF") Sub AnimationForm_Load(sender As Object, e As EventArgs)   ' Check whether image supports animation   If ImageAnimator.CanAnimate(gif) Then       ' Subscribe to event indicating the next        ' frame should be shown       ImageAnimator.Animate(gif, New EventHandler(_           AddressOf gif_FrameChanged))   End If End Sub Sub gif_FrameChanged(sender As Object, e As EventArgs)   If Me.InvokeRequired Then       ' Transition from worker thread to UI thread       Me.BeginInvoke(New EventHandler(_           AddressOf gif_FrameChanged), _           New Object() { sender, e })   Else       ' Trigger Paint event to draw next frame       Me.Invalidate()   End If End Sub Sub AnimationForm_Paint(sender As Object, e As PaintEventArgs)   ' Update image's active frame   ImageAnimator.UpdateFrame(gif)   ' Draw image's current frame   Dim g As Graphics = e.Graphics   g.DrawImage(gif, Me.ClientRectangle) End Sub 

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 Dim displayGraphics As Graphics = Me.CreateGraphics() ' Create bitmap to draw into based on existing Graphics object Dim myimage As 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:

 
 Dim imageGraphics As Graphics = 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:

 
 NotInheritable Class ImageFormat   ' Constructors   Public Sub New(aguid As Guid)   ' Properties   Property Guid() As Guid   Shared Property Bmp() As ImageFormat   Shared Property Emf() As ImageFormat   Shared Property Exif() As ImageFormat   Shared Property Gif() As ImageFormat   Shared Property Icon() As ImageFormat   Shared Property Jpeg() As ImageFormat   Shared Property MemoryBmp() As ImageFormat   Shared Property Png() As ImageFormat   Shared Property Tiff() As ImageFormat   Shared Property Wmf() As ImageFormat End Class 

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:

 
 Sub saveButton_Click(sender As Object, e As EventArgs)   Dim rect As Rectangle = New Rectangle(0, 0, 100, 100)   ' Get current graphics object for display   Dim displayGraphics As Graphics = Me.CreateGraphics   ' Create bitmap to draw into based on existing Graphics object   Dim myimage As Image = New Bitmap(rect.Width, rect.Height, _                         displayGraphics)   ' Wrap Graphics object around image to draw into   Dim imageGraphics As Graphics = Graphics.FromImage(image)   imageGraphics.FillRectangle(Brushes.Black, rect)   Dim format As StringFormat = 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") End Sub 
Figure 4.32. Example of Drawing to an Image

Icons

Before we wrap up the images section, we 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:

 
 NotInheritable Class Icon   Inherits MarshalByRefObject   Implements ISerializable   Implements ICloneable   Implements IDisposable   ' Constructors   Public Sub New(fileName As String)   Public Sub New(original As Icon, size As Size)   Public Sub New(original As Icon, width As Integer, _       height As Integer)   Public Sub New(stream As Stream)   Public Sub New(stream As Stream, width As Integer, _       height As Integer)   Public Sub New(type As Type, resource As String)   ' Properties   Property Handle As IntPtr   Property Height As Integer   Property Size As Size   Property Width As Integer   ' Methods   Shared Function FromHandle(handle As IntPtr) As Icon   Sub Save(outputStream As Stream)   Function ToBitmap() As Bitmap End Class 

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:

 
 Dim ico As Icon = New Icon("POINT10.ICO") g.DrawIcon(ico, Me.ClientRectangle) ' Stretch g.DrawIconUnstretched(ico, Me.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 icons, doesn't derive from the Image base class:

 
 NotInheritable Class Cursor   Implements IDisposable   Implements ISerializable   ' Contructors   Public Sub New(fileName As String)   Public Sub New(handle As IntPtr)   Public Sub New(stream As Stream)   Public Sub New(type As Type, resource As String)   ' Properties   Shared Property Clip() As Rectangle   Shared Property Current() As Cursor   Property Handle() As IntPtr   Shared Property Position() As Point   Property Size() As Size   ' Methods   Function CopyHandle() As IntPtr   Sub Draw(g As Graphics, targetRect As Rectangle)   Sub DrawStretched(g As Graphics, targetRect As Rectangle)   Shared Sub Hide()   Shared Sub Show() End Class 

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:

 
 Sub Form1_Click(sender As Object, e As EventArgs)   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 = Me.Cursor   End Try   ' Cursor restored after this event handler anyway... End Sub 

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:

 
 Sub InitializeComponent()   ...   Me.Cursor = System.Windows.Forms.Cursors.Cross   ... End Sub 

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 Visual Basic .NET
Windows Forms Programming in Visual Basic .NET
ISBN: 0321125193
EAN: 2147483647
Year: 2003
Pages: 139

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