Changing the Opacity of a Bitmap image

前端 未结 4 1336
暗喜
暗喜 2020-12-05 04:58

I have a form which has a image. I am using a slider to change the opacity of the image. So in the \"ValueChanged\" event of the slider I am calling the following method to

4条回答
  •  天命终不由人
    2020-12-05 05:34

    You loop over the pixels and play only the alpha channel. If you do this with Bitmap.LockBits it will actually be very fast.

        private const int bytesPerPixel = 4;
    
        /// 
        /// Change the opacity of an image
        /// 
        /// The original image
        /// Opacity, where 1.0 is no opacity, 0.0 is full transparency
        /// The changed image
        public static Image ChangeImageOpacity(Image originalImage, double opacity)
        {
            if ((originalImage.PixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed)
            {
                // Cannot modify an image with indexed colors
                return originalImage;
            }
    
            Bitmap bmp = (Bitmap)originalImage.Clone();
    
            // Specify a pixel format.
            PixelFormat pxf = PixelFormat.Format32bppArgb;
    
            // Lock the bitmap's bits.
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf);
    
            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;
    
            // Declare an array to hold the bytes of the bitmap.
            // This code is specific to a bitmap with 32 bits per pixels 
            // (32 bits = 4 bytes, 3 for RGB and 1 byte for alpha).
            int numBytes = bmp.Width * bmp.Height * bytesPerPixel;
            byte[] argbValues = new byte[numBytes];
    
            // Copy the ARGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, numBytes);
    
            // Manipulate the bitmap, such as changing the
            // RGB values for all pixels in the the bitmap.
            for (int counter = 0; counter < argbValues.Length; counter += bytesPerPixel)
            {
                // argbValues is in format BGRA (Blue, Green, Red, Alpha)
    
                // If 100% transparent, skip pixel
                if (argbValues[counter + bytesPerPixel - 1] == 0)
                    continue;
    
                int pos = 0;
                pos++; // B value
                pos++; // G value
                pos++; // R value
    
                argbValues[counter + pos] = (byte) (argbValues[counter + pos] * opacity);
            }
    
            // Copy the ARGB values back to the bitmap
            System.Runtime.InteropServices.Marshal.Copy(argbValues, 0, ptr, numBytes);
    
            // Unlock the bits.
            bmp.UnlockBits(bmpData);
    
            return bmp;
        }
    

提交回复
热议问题