This is a simple tip/trick which enables you to change Opacity of Image using C# by using
System.Drawing and
System.Drawing.Imaging NameSpaces.
Take a look at 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 has two parameters including
img for Image on which opacity will 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); 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(); 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);
To learn how to use the given code in your program:
Click
here[
^] to download source code.
[Edited-"Adding Reference Link"]
Reference Article:
There-Image Opacity Using C#[
^]