Skip to content

Instantly share code, notes, and snippets.

@xinmyname
Created January 12, 2012 18:58
Show Gist options
  • Select an option

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

Select an option

Save xinmyname/1602389 to your computer and use it in GitHub Desktop.
AForge filter to convert a gray scale image to RGBA using source as alpha and user specified color for RGB
using AForge.Imaging;
using AForge.Imaging.Filters;
namespace TextImage
{
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
public sealed class ColorizedAlpha : BaseFilter
{
public Color Color { get; set; }
// private format translation dictionary
private readonly Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>();
public override Dictionary<PixelFormat, PixelFormat> FormatTranslations
{
get { return formatTranslations; }
}
public ColorizedAlpha(Color color)
{
Color = color;
// initialize format translation dictionary
formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format32bppArgb;
}
protected override unsafe void ProcessFilter(UnmanagedImage sourceData, UnmanagedImage destinationData)
{
// get width and height
int width = sourceData.Width;
int height = sourceData.Height;
int srcOffset = sourceData.Stride - width;
int dstOffset = destinationData.Stride - width * 4;
// do the job
var src = (byte*)sourceData.ImageData.ToPointer();
var dst = (byte*)destinationData.ImageData.ToPointer();
// for each line
for (int y = 0; y < height; y++)
{
// for each pixel
for (int x = 0; x < width; x++, src++, dst += 4)
{
dst[RGB.A] = *src;
if (*src > 0)
{
dst[RGB.R] = Color.R;
dst[RGB.G] = Color.G;
dst[RGB.B] = Color.B;
}
else
dst[RGB.R] = dst[RGB.G] = dst[RGB.B] = 0;
}
src += srcOffset;
dst += dstOffset;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment