Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » GDI+ & Graphics » Image Attributes and the ImageAttributes Class in GDI+

Image Attributes and the ImageAttributes Class in GDI+


In this article I will explain about Image Attributes and the ImageAttributes Class in GDI+.

Author Rank:
Total page views :  1135
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


This article has been excerpted from book "Graphics Programming with GDI+".

Images represented by the Image class and its inherited classes can also store attributes. The ImageAttributes class represents the attributes of an image. DrawImage can take a parameter of type ImageAttributes, which represents how the colors are applied to an image shown it is rendered. The ImageAttributes class has no properties, but it provides many useful methods. Let's take a look at the method provided by the ImageAttributes class.

The SetWrapMode Method

Sometimes we need to fill a graphics shape with a texture that's smaller or large than the graphics shape. The wrap mode-represented by the WrapMode enumeration-specifies how a texture is tiled when it is larger or smaller than the area being filled. The members of the WrapMode enumeration are described in Table 8.7.

SetWrapMode is used to set the wrap mode of a texture or gradient. This method takes three parameters: a wrap mode (WrapMode), a color (Color), and a clamp (Boolean). The last two parameters are optional. If the clamp value is true, the texture will be clamped to the image boundary; otherwise there is no clamping.

Listing 8.9 uses this method. First we create an ImageAttributes object and set the wrap mode using SetWrapMode. Then we create an Image object using FromFile, followed by a call to DrawImage with an argument of the ImageAttributes object. DrawImage draws an image on the form, rendered using the colors defined by ImageAttributes.

TABLE 8.7: WrapMode members

Member

Description

Clamp

Clams the texture or gradient to the object boundary.

Title

Tiles the gradient or texture.

TileFlipX

Reverse the texture or gradient horizontally and then tiles it.

TileFlipXY

Reverse the texture or gradient horizontally and vertically then tiles it.

TileFlipY

Reverse the texture or gradient vertically and then tiles it.

LISTING 8.9: Using the SetWrapMode method of ImageAttributes

private void SetWrapMode_Click (object sender System.EventArgs e)
{
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);

            // Create ImageAttributes object
             ImageAttributes ImgAttr = new ImageAttributes();

            // Set wrap mode to tile
             ImgAttr.SetWrapMode(WrapMode.Tile);

            // Create an image
            Image curImage = Image.FromFile("dnWatcher.gif");

            // Draw image
            Rectangle rect = new Rectangle(0, 0, 400, 400);
             g.DrawImage(curImage, rect, 0, 0, 400, 400,
            GraphicsUnit.Pixel, ImgAttr);

            // Dispose of object
            g.Dispose();
}

Figure 8.8 shows the output from Listing 8.9. If the image is smaller than the surface, images are wrapped

Note: The WrapMode enumeration is defined in the System.Drawing.Drawing2D namespace. Don't forget to add the namespace reference to the project.

Figure 8.8.jpg

FIGURE 8.8: Wrapping images

The SetGamma Method

The SetGamma method sets the gamma value, which represents the brightness of a graphics shape, for all graphics objects, including images, brushes, and pens. Gamma values range from 0.1 to 5.0 (normally 0.1 to 2.2), with 0.1 being the brightest and 5.0 the darkest.

This method takes a floating type parameter as gamma value and a second optional parameter of the ColorAdjustType enumeration type. Using the ColorAdjustType enumeration from the Imaging namespace, you can even specify which GDI+ objects use this color adjustment. For example, if you want to apply gamma values on text only, you can do so using ColorAdjustType.Text, which is described in Table 8.8. The following code snippet sets the gamma value of ImageAttributes.

             ImageAttributes ImgAttr = new ImageAttributes();
             imageAttr.SetGamma(2.0f, ColorAdjustType.Default);

Now you can use this ImageAttributes object as a parameter of the DrawImage method.

The SetColorMatrix Method

A color matrix represents how colors are represented in an Image object. As we saw in Section 8.3.2, the ColorMatrix object represents a color matrix. 

TABLE 8.8: ColorAdjustType members

Member

Description

Any

Reserved

Bitmap

For Bitmap Object only

Brush

For Brush object only

Count

The number of types specified (used internally by GDI+)

Default

For all objects that do no have their own color adjustment information

Pen

For Pen objects only

Text

For text only

SetColorMatrix applies a color matrix to an image. This method takes a parameter of the ColorMatrix class, with two optional parameters of ColorMatrixFlag and ColorAdjustType enumeration.

Often we don't want all graphics objects to be affected by a color adjustment. Suppose we have some graphics shapes, an image, and some text, and we want only the image to be affected by the color adjustment specified by the SetColorMatrix method. The ColorAdjustType enumeration allows us to specify which graphics objects uses the color adjustment information. Table 8.8 describes the members of the ColorAdjustType enumeration.

ColorMatrixFlag specifies the types of images and colors that will be affected by the color adjustment settings. The ColorMatrixFlag enumeration has three members: AltGrays, Default, and SkipGrays. AltGrays is not available for use except by the .NET Framework internally, so basically ColorMatrixFlag provides the option of affecting gray colors or not. The Default value means that all colors will be affected; SkipGrays means that gray shades will not be affected. (You may want to skip some of the gray shades that are used when you're smoothing images.)

In Listing 8.10 we create ColorMatrix and ImageAttributes objects. Then we call SetColorMatrix to add a color matrix to ImageAttributes. ImageAttributes.SetColorMatrix takes ColorMatrix as its first argument. 

LISTING 8.10: Drawing semitransparent images

private void SetColorMatrix_Click ( object sender System.EventArgs e)
{
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);
            Rectangle rect = new Rectangle(20, 20, 200, 100);
            Bitmap bitmap = new Bitmap("MyPhoto.jpg");

            // Create an array of matrix points
            float[][] ptsArray =
{
      new float[] {1, 0, 0, 0, 0},
      new float[] {0, 1, 0, 0, 0},
      new float[] {0, 0, 1, 0, 0},
      new float[] {0, 0, 0, 0.5f, 0},
      new float[] {0, 0, 0, 0, 1}};

            // Create a color matrix
            ColorMatrix clrMatrix = new ColorMatrix(ptsArray);

            // Set ColorMatrix properties
            if (clrMatrix.Matrix34 <= 0.5)
            {
                 clrMatrix.Matrix34 = 0.8f;
                 clrMatrix.Matrix11 = 0.3f;
            }

            // Create image attributes
             ImageAttributes imgAttributes = new ImageAttributes();

            // Set color matrix
             imgAttributes.SetColorMatrix(clrMatrix,
             ColorMatrixFlag.Default,
             ColorAdjustType.Bitmap);
             g.FillRectangle(Brushes.Red, rect);
            rect.Y += 120;
            g.FillEllipse(Brushes.Black, rect);

            // Draw image
             g.DrawImage(bitmap,
            new Rectangle(0, 0, bitmap.Width, bitmap.Height),
            0, 0, bitmap.Width, bitmap.Height,
            GraphicsUnit.Pixel, imgAttributes);

            // Dispose of object
            g.Dispose();
}

Figure 8.9 shows the output from Listing 8.10. A rectangle and a circle are drawn, and then an image with lower color resolution, as specified by ImageAttributes.

Figure 8.9.jpg

FIGURE 8.9: Drawing semitransparent images

The SetNoOp and SetColorKey Methods

The SetNoOp method sets the NoOp correction value for Graphics objects. When NoOp is set, no adjustments to the color will be made during the rendering process.

SetColorKey sets the low and high color values for graphics objects and shapes. The SetColorKey method takes a parameter of type ColorAdjustType enumeration (see Table 8.8) that specifies the type of the graphics objects and shapes to be affected by SetColorKey.

Listing 8.11 applies gamma effect and sets color key values using the SetColorKey method.

LISTING 8.11: Applying SetGamma and SetColorKey

private void SetNoOp_Click (object sender, System.EventArgs e)
{
            // Create a Graphics object
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);

            // Create two colors
            Color lClr = Color.FromArgb(245, 0, 0);
            Color uClr = Color.FromArgb(255, 0, 0);

            // Create ImageAttributes object
             ImageAttributes ImgAttr = new ImageAttributes();

            // Set color key
             ImgAttr.SetColorKey(lClr, uClr,
             ColorAdjustType.Default);

            // Set gamma
             ImgAttr.SetNoOp(ColorAdjustType.Default);

            // Create an Image object
            Image curImage = Image.FromFile("dnWatcher.gif");

            // Draw image
            Rectangle rect = new Rectangle(0, 0, 400, 400);
             g.DrawImage(curImage, rect, 0, 0, 400, 400,
            GraphicsUnit.Pixel, ImgAttr);

            // Dispose of object
            g.Dispose();
}

Figure 8.10 shows the output from Listing 8.11.

Now if we uncomment the following line in Listing 8.11:

            //ImgAttr.SetNoOp (ColorAdjustType.Defualt);

the output will look like Figure 8.11. Using SetNoOp cancels all image attribute effects.

The SetThreshold Method

The SetThreshold method sets the transparency range (threshold) for a specified category. This method takes one parameter representing a threshold value ranging between 0.0 and 1.0, and an optional second parameter of type ColorAdjustType. The value of the threshold specifies a cutoff point for each component of color. For example, suppose that the threshold is set to 0.8 and the value of the red component is 240. Because the value of the red component (240) is greater than 0.8, the red component will be changed to 255 (full intensity).

             imageAttr.SetThreshold(0.8f, ColorAdjustType.Default);

Figure 8.10.jpg

FIGURE 8.10: Applying SetGamma and SetColorKey

Figure-8.11.jpg

FIGURE 8.11: Using the SetNoOp method

The SetBrushRemapTable Method

We have already discussed how the SetRemapTable method sets a remap table to the specified ColorMap object. The OldColor and NewColor properties of ColorMap represents old and new colors, respectively. SetBrushRemapTable converts only the colors of brushes. The ColorMap class also provides both ColorMap and NewColor properties.
Listing 8.12 creates a ColorMap object, sets its OldColor and NewColor properties, and then calls SetBrushRemapTable with the ColorMap object.

LISTING 8.12: Using SetBrushRemapTable

private void SetBrushRemapTable_Click (object sender System.EventArgs e)
{
            Graphics g = this.CreateGraphics();
            g.Clear(this.BackColor);
            ColorMap[] clrMapTable = new ColorMap[1];
            clrMapTable[0] = new ColorMap();
            clrMapTable[0] = OldColor = Color.Red;
            clrMapTable[0] = NewColor = Color.Green;
             ImageAttributes ImgAttr = new ImageAttributes();
             ImgAttr.SetBrushRemapTable(clrMapTable);
            Image curImage = Image.FromFile("Simple.bmp");
             g.DrawImage(curImage, 0, 0);
            Rectangle rect = new Rectangle(0, 0, 400, 400);
             g.DrawImage(curImage, rect, 0, 0, 400, 400,
            GraphicsUnit.Pixel, ImgAttr);

            // Dispose of object
            g.Dispose();
}

The Clear Methods

The ImageAttributes class provides a "clear" method for almost every set method we have discussed in this section. The clear methods take either no parameter or an optional parameter of ColorAdjustType enumeration. These clear methods are listed in Table 8.9.

TABLE 8.9: The clear methods of ImageAttributes

Method

Description

ClearBrushRemapTable

Clears color remap table for brush.

ClearColorKey

Clears color key values for the graphics objects specified by the ColorAdjustType enumeration.

ClearColorMatrix

Clears color adjust matrix to all zeros.

ClearGamma

Clears gamma effect for the graphics objects specified by the ColorAdjustType enumeration.

ClearNoOp

Clears NoOp setting for all graphics objects.

ClearOutputChannel

Clears output channel selection for graphics objects specified by the ColorAdjustType enumeration.

ClearOutputChannelColorProfile

Clears output channel section and color profile file for graphics objects specified by the ColorAdjustType enumeration.

ClearRemapTable

Clears color remap table for graphics objects specified by the ColorAdjustType enumeration.

ClearThreshold

Clears threshold values for graphics objects specified by the ColorAdjustType enumeration.

Suppose that we wanted to clear the color key values for all graphics objects. We would use the ClearColorKey method as follows:

             imageAttr.ClearColorKey(ColorAdjustType.Default);

Conclusion

Hope the article would have helped you in understanding Image Attributes and the ImageAttributes Class in GDI+. Read other articles on GDI+ on the website.

bookGDI.jpg
This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.


Login to add your contents and source code to this article
 About the author
 
Puran Mehra

Working as a Software professional. 

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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
DevExpress Free UI Controls
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.