One exampple of how to change image opacity:
private Image SetImageOpacity(Image image, float opacity)
{
try
{
//create a Bitmap the size of the image provided
Bitmap bmp = new Bitmap(image.Width, image.Height);
//create a graphics object from the image
using (Graphics gfx = Graphics.FromImage(bmp))
{
//create a color matrix object
ColorMatrix matrix = new ColorMatrix();
//set the opacity
matrix.Matrix33 = opacity;
//create image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color(opacity) of the image
attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
//now draw the image
gfx.DrawImage(image
, new Rectangle(0
, 0
, bmp.Width
, bmp.Height
)
, 0
, 0
, image.Width
, image.Height
, GraphicsUnit.Pixel
, attributes
);
}
return bmp;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
My example how use this method:
try
{
float opacity = (float) trackBar1.Value / 100;
panel1.BackgroundImageLayout = ImageLayout.Center;
panel1.BackgroundImage = SetImageOpacity(myBitmap, opacity);
}
catch (Exception exception)
{
MessageBox.Show($@"Cannot to set opacity of picture. Error message: {exception.Message}");
}
Notice that opacity is float and it can be between 0 to 1, everything bigger then 1 will have no impact. Example in Winforms you can download from
here.
Taken from
here.