public static UnmanagedImage GetFilledImage(int width, int height, PixelFormat pixelFormat, Color color)
{
UnmanagedImage filledImage;
var grayImage = UnmanagedImage.Create(width, height, PixelFormat.Format8bppIndexed);
if (pixelFormat == PixelFormat.Format8bppIndexed ||
pixelFormat == PixelFormat.Format16bppGrayScale)
{
SystemTools.SetUnmanagedMemory(
grayImage.ImageData,
(color.R + color.G + color.B) / 3,
grayImage.Stride * grayImage.Height);
filledImage = pixelFormat == PixelFormat.Format8bppIndexed ? grayImage.Clone() :
UnmanagedImage.FromManagedImage(
Accord.Imaging.Image.Convert8bppTo16bpp(grayImage.ToManagedImage(false)));
}
else
{
filledImage = UnmanagedImage.Create(width, height, pixelFormat);
if (pixelFormat == PixelFormat.Format24bppRgb)
{
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.R, grayImage.Stride * grayImage.Height);
var replaceChannel = new ReplaceChannel(RGB.R, grayImage);
replaceChannel.ApplyInPlace(filledImage);
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.G, grayImage.Stride * grayImage.Height);
replaceChannel.Channel = RGB.G;
grayImage.Copy(replaceChannel.UnmanagedChannelImage);
replaceChannel.ApplyInPlace(filledImage);
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.B, grayImage.Stride * grayImage.Height);
replaceChannel.Channel = RGB.B;
grayImage.Copy(replaceChannel.UnmanagedChannelImage);
replaceChannel.ApplyInPlace(filledImage);
}
else
{
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.R, grayImage.Stride * grayImage.Height);
UnmanagedImage grayImage16 = UnmanagedImage.FromManagedImage(
Accord.Imaging.Image.Convert8bppTo16bpp(grayImage.ToManagedImage(false)));
ReplaceChannel replaceChannel = new ReplaceChannel(RGB.R, grayImage16);
replaceChannel.ApplyInPlace(filledImage);
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.G, grayImage.Stride * grayImage.Height);
replaceChannel.Channel = RGB.G;
replaceChannel.UnmanagedChannelImage.Dispose();
replaceChannel.UnmanagedChannelImage =
UnmanagedImage.FromManagedImage(Accord.Imaging.Image.Convert8bppTo16bpp(
grayImage.ToManagedImage(false)));
replaceChannel.ApplyInPlace(filledImage);
SystemTools.SetUnmanagedMemory(grayImage.ImageData, color.B, grayImage.Stride * grayImage.Height);
replaceChannel.Channel = RGB.B;
replaceChannel.UnmanagedChannelImage.Dispose();
replaceChannel.UnmanagedChannelImage =
UnmanagedImage.FromManagedImage(Accord.Imaging.Image.Convert8bppTo16bpp(
grayImage.ToManagedImage(false)));
replaceChannel.ApplyInPlace(filledImage);
replaceChannel.UnmanagedChannelImage.Dispose();
grayImage16.Dispose();
}
}
grayImage.Dispose();
return filledImage;
}
}