Advertisement
housec84

CleanIfTransparent

Jul 27th, 2011
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. public static long CleanIfTransparent(Bitmap bmp)
  2.         {
  3.             long rtn = 0;
  4.             //does our image contain an alpha channel?
  5.             if ((bmp.Flags & 0x2) != 0 && bmp.PixelFormat == PixelFormat.Format32bppArgb)
  6.             {
  7.                 //get int pointer to bmp.
  8.                 BitmapData bData = bmp.LockBits(
  9.                     new Rectangle(0, 0, bmp.Width, bmp.Height),
  10.                     ImageLockMode.ReadOnly,
  11.                     PixelFormat.Format32bppArgb);
  12.                 IntPtr iptr = bData.Scan0;
  13.  
  14.                 //get byteCount of bmp.
  15.                 int len = bmp.Height * Math.Abs(bData.Stride) / 4;
  16.  
  17.                 unsafe
  18.                 {
  19.                     //get pointer from intpointer
  20.                     byte* ptr = (byte*)iptr.ToPointer();
  21.                     //loop through image.
  22.                     for (int i = 0; i < len; i++)
  23.                     {
  24.                         //the pixel value in bgra
  25.                         //inverse alpha
  26.                         byte a = (Byte)(0xFF - (*(ptr + 3)));
  27.                         //do we have a value for our alpha?
  28.                         if (a > 0)
  29.                         {
  30.                             rtn++;
  31.                             //blue
  32.                             *ptr = (byte)(Math.Min(*ptr + a, 255));
  33.                             ptr++;
  34.                             //green
  35.                             *ptr = (byte)(Math.Min(*ptr + a, 255));
  36.                             ptr++;
  37.                             //red
  38.                             *ptr = (byte)(Math.Min(*ptr + a, 255));
  39.                             ptr++;
  40.                             //alpha
  41.                             *ptr = 0xFF;
  42.                         }
  43.                         else
  44.                         {
  45.                             ptr = ptr + 3;
  46.                         }
  47.  
  48.                         if (i < len - 1)
  49.                         {
  50.                             ptr++;
  51.                         }
  52.                     }
  53.                 }
  54.                 bmp.UnlockBits(bData);
  55.             }
  56.             return rtn;
  57.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement