public void DrawWatermark(Image original, Bitmap watermark,
WatermarkPosition position, Color transparentColor, float opacity)
{
if (original == null )
throw new ArgumentNullException( "original" );
if (watermark == null )
throw new ArgumentNullException( "watermark" );
if (opacity < 0 || opacity > 1)
throw new ArgumentOutOfRangeException( "Watermark opacity value is out of range" );
Rectangle dest = new Rectangle(
GetDestination(original.Size, watermark.Size, position), watermark.Size);
using ( Graphics g = Graphics .FromImage(original))
{
ImageAttributes attr = new ImageAttributes();
ColorMatrix matrix = new ColorMatrix( new float [][] {
new float [] { opacity, 0f, 0f, 0f, 0f },
new float [] { 0f, opacity, 0f, 0f, 0f },
new float [] { 0f, 0f, opacity, 0f, 0f },
new float [] { 0f, 0f, 0f, opacity, 0f },
new float [] { 0f, 0f, 0f, 0f, opacity } });
attr.SetColorMatrix(matrix);
watermark.MakeTransparent(transparentColor);
g.DrawImage(watermark, dest, 0, 0, watermark.Width, watermark.Height,
GraphicsUnit.Pixel, attr, null , IntPtr .Zero);
g.Save();
}
}
* This source code was highlighted with Source Code Highlighter .
public enum WatermarkPosition
{
TopLeft = 0,
TopRight,
BottomLeft,
BottomRight,
Middle
}
* This source code was highlighted with Source Code Highlighter .
private static Point GetDestination(Size originalSize, Size watermarkSize, WatermarkPosition position)
{
Point destination = new Point(0, 0);
switch (position)
{
case WatermarkPosition.TopRight:
destination.X = originalSize.Width - watermarkSize.Width;
break ;
case WatermarkPosition.BottomLeft:
destination.Y = originalSize.Height - watermarkSize.Height;
break ;
case WatermarkPosition.BottomRight:
destination.X = originalSize.Width - watermarkSize.Width;
destination.Y = originalSize.Height - watermarkSize.Height;
break ;
case WatermarkPosition.Middle:
destination.X = (originalSize.Width - watermarkSize.Width) / 2;
destination.Y = (originalSize.Height - watermarkSize.Height) / 2;
break ;
}
return destination;
}
* This source code was highlighted with Source Code Highlighter .
watermark.MakeTransparent(transparentColor);
) and expand the watermark type to Image.Source: https://habr.com/ru/post/41546/
All Articles