Change Opacity of Image in C#

This is a Simple Tips/Tricks which enable you to change Opacity of Image using C# by using  System.Drawing  and  System.Drawing.Imaging  NameSpaces.
Take a look how ChangeOpacity(Image img, float opacityvalue) Method will enable you to change opacity of Image.
In this given code System.Drawing Namespace is used to access Bitmap and Graphics classes whereas System.Drawing.Imaging Namespaces is used to access ColorMatrix and ImageAttributes.
ChangeOpacity Method having two parameter including img for Image on which opaicty will be apply  and  opacityvalue for set opacity level of form.

using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace ImageUtils
{
    class ImageTransparency
    {
        public static Bitmap ChangeOpacity(Image img, float opacityvalue)
        {
            Bitmap bmp = new Bitmap(img.Width,img.Height); // Determining Width and Height of Source Image
            Graphics graphics = Graphics.FromImage(bmp);
            ColorMatrix colormatrix = new ColorMatrix();
            colormatrix.Matrix33 = opacityvalue;
            ImageAttributes imgAttribute = new ImageAttributes();
            imgAttribute.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            graphics.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgAttribute);
            graphics.Dispose();   // Releasing all resource used by graphics
            return bmp;
        }
    }
}

When you will use this Method in your program to change opacity of an image in pictureBox control. You need to write code as given below


float opacityvalue = float.Parse(txtopacityvalue.Text) / 100;
pictureBox1.Image = ImageUtils.ImageTransparency.ChangeOpacity(Image.FromFile("filename"),opacityvalue);  //calling ChangeOpacity Function

To learn how to use given code in your program
Click here to download source code.

Enjoy Coding  🙂

Advertisements

About Ravi Ranjan Kumar

An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.
This entry was posted in .Net, C#, Tips&Tricks and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s