Skip to content

Instantly share code, notes, and snippets.

@xinmyname
Created January 12, 2012 19:00
Show Gist options
  • Select an option

  • Save xinmyname/1602395 to your computer and use it in GitHub Desktop.

Select an option

Save xinmyname/1602395 to your computer and use it in GitHub Desktop.
AForge filter to perform Screen filter (ala Photoshop)
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using AForge.Imaging;
using AForge.Imaging.Filters;
namespace TextImage
{
public class Screen : BaseInPlaceFilter2
{
private Dictionary<PixelFormat, PixelFormat> _formatTranslations;
public Screen(Bitmap overlayImage)
: base(overlayImage)
{
InitFormatTranslations();
}
public Screen(UnmanagedImage overlayImage)
: base(overlayImage)
{
InitFormatTranslations();
}
private void InitFormatTranslations()
{
_formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
_formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb;
_formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb;
_formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed;
}
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get { return _formatTranslations; }
}
protected override unsafe void ProcessFilter(UnmanagedImage image, UnmanagedImage overlay)
{
// get image dimension
int width = image.Width;
int height = image.Height;
// initialize other variables
int pixelSize = 0;
switch (image.PixelFormat)
{
case PixelFormat.Format32bppArgb: pixelSize = 4; break;
case PixelFormat.Format24bppRgb: pixelSize = 3; break;
case PixelFormat.Format8bppIndexed: pixelSize = 1; break;
}
int lineSize = width * pixelSize;
int offset = image.Stride - lineSize;
int ovrOffset = overlay.Stride - lineSize;
// do the job
var ptr = (byte*)image.ImageData.ToPointer();
var ovr = (byte*)overlay.ImageData.ToPointer();
// for each line
for (int y = 0; y < height; y++)
{
// for each pixel
for (int x = 0; x < lineSize; x++, ptr++, ovr++)
{
// C = 1 - (1-A)*(1-B)
// double a = *ptr/255.0;
// double b = *ovr/255.0;
// double c = 1.0 - (1.0 - a)*(1.0 - b);
// *ptr = (byte)(c * 255.0);
*ptr = (byte)(255 - ((255 - *ptr) * (255 - *ovr)) / 255);
}
ptr += offset;
ovr += ovrOffset;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment