12,693,891 members (31,947 online)
alternative version

29.2K views
22 bookmarked
Posted

# Quick n' Dirty Alpha Mask Generator

, 15 Mar 2007 CPOL
 Rate this:
A quick-to-implement method for generating an alpha mask from a flat image file with no alpha channel

## Introduction

During a recent project at work, I needed a quick solution to apply transparency on-the-fly to a flat raster image provided by the user. After Googling like a mad man for ten minutes, I opted for a hand-rolled solution. This app demonstrates the use of the exceptionally inefficient, but effective result.

## Using the Code

The sample app's single method goes through the source image pixel-by-pixel, takes a sampling of the surrounding pixels, and uses the mathematical mean of this sampling to calculate the base alpha value for that pixel. The lighter the sampling, the lower the calculated alpha value... e.g. a sampling that equals pure white would render the given pixel as fully transparent (alpha 0).

```for(int i=0; i<9; i++)
{
Color sample;
//SOOOOOOO inefficient!
switch(i)
{
//TopLeft
case 0:
sample = (x>0 && y>0) ?
oldBitmap.GetPixel(x-1,y-1) :
oldBitmap.GetPixel(x,y);
sampleGrid[i] = (sample.R + sample.G + sample.B)/3;
break;

//TopCenter
case 1:
sample = (y>0) ?
oldBitmap.GetPixel(x,y-1) :
oldBitmap.GetPixel(x,y);
sampleGrid[i] = (sample.R + sample.G + sample.B)/3;
break;

/* etc., etc. */    ```

It then weighs that pixel's computed alpha value against a user-set threshold... if the value is above the threshold, the pixel is given full opacity (alpha 255). This could be easily modified to treat the darker parts of an image as transparent.

```int A = 0;
for(int i=0; i<9; i++)
A += sampleGrid[i];

A = 255 - (A/9);
if (A > (int)this.numThreshold.Value)
A = 255;

newBitmap.SetPixel(x,y, Color.FromArgb(A, color));
```

## Points of Interest

I am quite certain that there are better ways to have implemented this, but I was on an insanely tight schedule, and this sufficed for the task at hand. If anyone would care to demonstrate a better implementation, I would greatly appreciate your feedback.

## History

• 15th March, 2007: Initial post

## Share

 Software Developer the patchwerks United States
No Biography provided

## You may also be interested in...

 Pro

 First Prev Next
 Nice work stixoffire22-Mar-07 7:55 stixoffire 22-Mar-07 7:55
 maketransparent PuReBRaiNZ19-Mar-07 13:54 PuReBRaiNZ 19-Mar-07 13:54
 Re: maketransparent patch_werk1-Apr-07 6:55 patch_werk 1-Apr-07 6:55
 FastBitmap Patrick Sears16-Mar-07 7:22 Patrick Sears 16-Mar-07 7:22
 Re: FastBitmap CarlosMMartins20-Mar-07 0:44 CarlosMMartins 20-Mar-07 0:44
 Re: FastBitmap stixoffire22-Mar-07 7:50 stixoffire 22-Mar-07 7:50
 Re: FastBitmap Patrick Sears22-Mar-07 11:19 Patrick Sears 22-Mar-07 11:19
 Last Visit: 31-Dec-99 19:00     Last Update: 18-Jan-17 14:56 Refresh 1