Masks a bitmap by combining its alpha with the provided alpha mask. - CSharp System.Drawing

CSharp examples for System.Drawing:Bitmap

Description

Masks a bitmap by combining its alpha with the provided alpha mask.

Demo Code


using System.Drawing.Imaging;
using System.Drawing;
using System.Collections;
using System;//from w  w  w  .j  a  v  a 2 s  .  c o  m

public class Main{
    /// <summary>
      /// Masks a bitmap by combining its alpha with the provided alpha mask.
      /// </summary>
      /// <param name="bmpDst">32-bit</param>
      /// <param name="bmpMask">8-bit grayscale</param>
      public static void Mask(Bitmap bmpDst, Bitmap bmpMask)
      {
         Bitmap bmpSrc = bmpMask;

         System.Drawing.Imaging.BitmapData dataSrc = bmpSrc.LockBits(new Rectangle(new Point(0,0), bmpSrc.Size),
            System.Drawing.Imaging.ImageLockMode.ReadOnly, bmpSrc.PixelFormat);

         System.Drawing.Imaging.BitmapData dataDst = bmpDst.LockBits(new Rectangle(new Point(0,0), bmpSrc.Size),
            System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpDst.PixelFormat);

         int nBytesPerPix = GetBytesPerPixel(bmpDst);
         unsafe
         {
            int nWidthSrc = bmpSrc.Width*1;
            int nWidthDst = bmpDst.Width*nBytesPerPix;
            byte* ptrSrc = ((byte*)dataSrc.Scan0);
            byte* ptrDst = ((byte*)dataDst.Scan0) + 3; //alpha is 4th byte (?)
            for (int y=0; y<bmpSrc.Height; y++)
            {
               for (int x=0; x<bmpSrc.Width; x++)
               {
                  //ucTemp = (unsigned char)((unsigned int)pPSrc1[ulS1P+3]*(255-pPSrc2[ulS2P+3]) >> 8);
                  //pPDst[ulDP+3] = ucTemp + pPSrc2[ulS2P+3];
                  *ptrDst = Math.Min(*ptrDst,*ptrSrc);
//                  byte val = (byte)((uint)*ptrSrc*(255-*ptrDst) >> 8);
//                  *ptrDst = (byte)(val + *ptrDst);
                  ptrSrc++;
                  ptrDst+=nBytesPerPix;
               }
               ptrSrc+=dataSrc.Stride-nWidthSrc;
               ptrDst+=dataDst.Stride-nWidthDst + (bmpDst.Width-bmpSrc.Width)*nBytesPerPix;
            }
         }
         bmpSrc.UnlockBits(dataSrc);
         bmpDst.UnlockBits(dataDst);
      }
    public static int GetBytesPerPixel(Bitmap bmp)
      {
         //TODO: 16-bit, eg PixelFormat.Format16bppArgb1555
         return (bmp.PixelFormat == PixelFormat.Format24bppRgb)?3:
            ((bmp.PixelFormat == PixelFormat.Format8bppIndexed)?1:4);
      }
}

Related Tutorials