Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You loop over the pixels and play only the alpha channel. If you do this with Bitmap.LockBits it will actually be very fast.</p> <pre><code> private const int bytesPerPixel = 4; /// &lt;summary&gt; /// Change the opacity of an image /// &lt;/summary&gt; /// &lt;param name="originalImage"&gt;The original image&lt;/param&gt; /// &lt;param name="opacity"&gt;Opacity, where 1.0 is no opacity, 0.0 is full transparency&lt;/param&gt; /// &lt;returns&gt;The changed image&lt;/returns&gt; public static Image ChangeImageOpacity(Image originalImage, double opacity) { if ((originalImage.PixelFormat &amp; 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 &lt; 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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload