In this article, I will be showing you a complex manipulation i.e Setting image Opacity of any Image, which you can learn and try to apply on other images. Now this tutorial requires you to be very clear with the concepts of how Images work and how in theory we can manipulate their properties like colours or opacity. Also you need to have some knowledge of Matrices from Mathematics. Even if you are not aware of these things, even then you can read this article, in which I have tried my best to explain how each line of code, image’s colour, opacity work.
Before reading this article, I recommend you to first read my another article on General Information On Image Manipulation. Because you will need that information to understand the code for this article.
- Add System.Drawing.Imaging namespace in your code
- First of all declare an instance of Image class, which will hold the Image whose Opacity we want to change. You can load any image from your disk using following line of code.
Image img = Image.FromFile(@"Your Image Path Here");
- Now create new instance of Bitmap and Graphics class. For Bitmap object specify the height and width you want. As I want to show the final image in PictureBox, so I have set the Bitmap object’s width and height equal to width and height of PictureBox.
Bitmap bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics graphic = Graphics.FromImage(bitmap);
- Now create new ColorMatrix class and assign the value to Matrix33 element of this instance equal to the opacity you want to set on the image. And how this Matrix33 element will work, I have described in my last article.
float f = .3F;
ColorMatrix colormatrix = new ColorMatrix();
colormatrix.Matrix33 = f;
- Now create new instance of ImageAttributes class. This instance will help us in applying the ColorMatrix settings on the final image.
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.SetColorMatrix(colormatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
- Now using the Graphics class object which we have already created in our code, draw and image using the following code.
graphic.DrawImage(img, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imageAttributes);
- Now the upper line of code will only draw the image in bitmap object by applying Image Attributes on the Image we have loaded from our disk. To show this image in PictureBox, just assign the Image property of PictureBox equal to the Bitmap object.
pictureBox1.Image = bitmap;
- These Graphics class object takes too much memory, so you should dispose them as well at the end.
- Here is sample output. First image is the actual image and 2nd image is after applying opacity.