Set Alpha Channel Value in Bitmap - CSharp System.Drawing

CSharp examples for System.Drawing:Image Operation

Description

Set Alpha Channel Value in Bitmap

Demo Code

//  ? Veler Software 2012. All rights reserved.
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Drawing;
using System;/* www. j a va  2  s .co m*/

public class Main{
        public static void SetAlphaChanelValue(Bitmap image, byte value)
        {
            if (image == null)
                throw new ArgumentNullException("image");
            if (image.PixelFormat != PixelFormat.Format32bppArgb)
                throw new ArgumentException("Wrong PixelFormat");

            BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                     ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            unsafe
            {
                PixelData* pPixel = (PixelData*)bitmapData.Scan0;
                for (int i = 0; i < bitmapData.Height; i++)
                {
                    for (int j = 0; j < bitmapData.Width; j++)
                    {
                        pPixel->A = value;
                        pPixel++;
                    }
                    pPixel += bitmapData.Stride - (bitmapData.Width * 4);
                }
            }
            image.UnlockBits(bitmapData);
        }
}

Related Tutorials