using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
namespace Sqt.VisualStudio.Util
{
///
/// Helpers for images and bitmap handling.
///
internal static class ImageHelper
{
///
/// Loads an embedded resource image.
///
/// The resource assembly usually the assembly of the code that calls this method.
/// The resource path.
///
internal static Image LoadEmbeddedImageResource( Assembly resourceAssembly, string resourcePath )
{
if ( String.IsNullOrEmpty( resourcePath ) )
throw new ArgumentNullException( "resourcePath" );
Stream stream = resourceAssembly.GetManifestResourceStream( resourcePath );
if ( stream == null ) {
throw new ArgumentException( "Can't find the resource " + resourcePath, "resourcePath" );
}
Image bitmap = Image.FromStream( stream );
return bitmap;
}
///
/// Masks an image and returns a two color bitmap.
///
/// The image to convert to a maskColor.
/// The color used for masking.
///
/// The color used when an image pixel has not a masking color.
/// If the value is the original color
/// will be used.
///
/// The colors to replace with the maskColor color.
///
internal static Image GetMask( Image image, Color maskColor, Color unmaskColor, params Color[] colorsToMask )
{
if ( image == null )
throw new ArgumentNullException( "image" );
if ( colorsToMask == null )
throw new ArgumentNullException( "colorsToMask" );
List colorsToMaskList = new List( colorsToMask );
bool isUnmaskDefined = unmaskColor != Color.Empty;
Bitmap bitmap = new Bitmap( image );
EqualColorPredicate equalColorPredicate = new EqualColorPredicate();
for ( int y = 0; y < bitmap.Height; y++ ) {
for ( int x = 0; x < bitmap.Width; x++ ) {
Color pixel = bitmap.GetPixel( x, y );
equalColorPredicate.Pixel = pixel;
if ( colorsToMaskList.Exists( equalColorPredicate.Matches ) )
bitmap.SetPixel( x, y, maskColor );
else if ( isUnmaskDefined )
bitmap.SetPixel( x, y, unmaskColor );
}
}
return bitmap;
}
///
/// Helper predicate to check color equality.
///
///
/// Its not possibile to use
/// because the methode returns false if one of the colors
/// compared is a named color and the other not, even if their
/// RGB and alpha values are the same.
///
private class EqualColorPredicate
{
private Color pixel;
public EqualColorPredicate()
{
}
public Color Pixel
{
get { return this.pixel; }
set { this.pixel = value; }
}
public bool Matches( Color color )
{
return color.R == Pixel.R && color.G == Pixel.G
&& color.B == Pixel.B && color.A == Pixel.A;
}
}
}
}