How to add simple water mark to images
While working on one of my friend’s blog, I got a chance to write a code snippet which helps to add water mark for all images automatically. And I created a simple library do this. I added few extra options, it may not work properly, I didn’t tested it
namespace dotnetthoughts.net
{
using System.Drawing;
/// <summary>
/// </summary>
public class WaterMarker
{
/// <summary>
/// Sets / Gets color of the Watermark text.
/// </summary>
public Color Color { get; set; }
/// <summary>
/// Sets or Gets Font of Watermark Text.
/// </summary>
public Font Font { get; set; }
/// <summary>
/// Sets or Gets Alpha value of the Color.
/// </summary>
/// <remarks>
/// It should be between 0 and 255.
/// </remarks>
public int Alpha { get; set; }
/// <summary>
/// Sets or Gets the Watermark Text
/// </summary>
public string WatermarkText { get; set; }
/// <summary>
/// Sets or Gets the alignment of Watermark text
/// </summary>
public ContentAlignment TextAlignment { get; set; }
/// <summary>
/// Creates an instance of Watermarker class.
/// </summary>
public WaterMarker()
{
Color = Color.White;
Alpha = 200;
Font = new Font(FontFamily.GenericSerif, 20);
WatermarkText = "dotnetthoughts.net";
TextAlignment = ContentAlignment.BottomCenter;
}
/// <summary>
/// Adds the watermark text to the given image.
/// </summary>
/// <param name="image">Image to apply watermark</param>
/// <param name="waterMarkText">Watermark Text</param>
/// <returns>Image</returns>
public Image Apply(Image image, string waterMarkText)
{
WatermarkText = waterMarkText;
using (Graphics graphics = Graphics.FromImage(image))
{
var size =
graphics.MeasureString(WatermarkText, Font);
var brush =
new SolidBrush(Color.FromArgb(Alpha, Color));
graphics.DrawString
(WatermarkText, Font, brush,
GetTextPosition(image, size));
}
return image;
}
/// <summary>
/// Adds the watermark text to the given image.
/// </summary>
/// <param name="image">Image to apply watermark</param>
/// <returns>Image</returns>
public Image Apply(Image image)
{
return Apply(image, WatermarkText);
}
private PointF GetTextPosition(Image image, SizeF size)
{
PointF point = default(PointF);
switch (TextAlignment)
{
case ContentAlignment.BottomCenter:
point = new PointF((image.Width - size.Width) / 2,
(image.Height - size.Height));
break;
case ContentAlignment.BottomLeft:
point = new PointF(0, (image.Height - size.Height));
break;
case ContentAlignment.BottomRight:
point = new PointF((image.Width - size.Width),
(image.Height - size.Height));
break;
case ContentAlignment.MiddleCenter:
point = new PointF((image.Width - size.Width) / 2,
(image.Height - size.Height) / 2);
break;
case ContentAlignment.MiddleLeft:
point = new PointF(0, (image.Height - size.Height) / 2);
break;
case ContentAlignment.MiddleRight:
point = new PointF((image.Width - size.Width),
(image.Height - size.Height) / 2);
break;
case ContentAlignment.TopCenter:
point = new PointF((image.Width - size.Width) / 2, 0);
break;
case ContentAlignment.TopLeft:
point = new PointF(0, 0);
break;
case ContentAlignment.TopRight:
point = new PointF((image.Width - size.Width), 0);
break;
}
return point;
}
}
}
Happy Coding
CaptureItPlus – A screen capture utility
Few days back I started working on another open source project, for capturing screen shots. It is similar or can be used as an alternative to Snipping Tool in Windows Vista / 7.
Here is the main features of CaptureItPlus
- Supports all major screen capture modes. Fullscreen, Window, Rectangle, FreeForm and Scheduled capture.
- Supports various output formats, JPG, PNG, GIF, BMP, WMF, and TIFF. Default format in PNG, but users can customize it using settings.
- Supports keyboard shortcuts(customization also) for capture modes
- Sound notification after capture.
- Supports capture screen with cursor.
- Written in Microsoft .Net 2.0; supports major operating systems.
- API support.
- Easy to install, no admin rights required.
- Support for executing plugins after screen capture.
- Licensed under GNU GPL v2.0. Full source code available(C# 2.0)
You can download latest version of CaptureItPlus from CodePlex.
Please try it and let me know your comments.
Image cropping control in C# for Windows Forms
This post is also inspired by a SO post – Image Cropping Control for WinForms with Selection Rectangle. I had done a similar implementation using VB.Net long back but I couldn’t remember the implementation.
Today I tried it again and here is an implementation, which helps to crop an Image using selection rectangle.
namespace dotnetthoughts
{
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class CustomPictureBox : PictureBox
{
private Rectangle _rectangle;
private Point _startingPoint;
private Point _finishingPoint;
private bool _isDrawing;
public CustomPictureBox()
{
Cursor = Cursors.Cross;
_startingPoint = new Point();
_finishingPoint = new Point();
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
{
_isDrawing = true;
_startingPoint = new Point(e.X, e.Y);
}
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Left && _isDrawing)
{
_finishingPoint = new Point(e.X, e.Y);
if (e.X > _startingPoint.X)
{
_rectangle = new Rectangle(
_startingPoint.X <= e.X ? _startingPoint.X : e.X,
_startingPoint.Y <= e.Y ? _startingPoint.Y : e.Y,
e.X - _startingPoint.X <= 0 ? _startingPoint.X - e.X : e.X - _startingPoint.X,
e.Y - _startingPoint.Y <= 0 ? _startingPoint.Y - e.Y : e.Y - _startingPoint.Y);
}
else
{
_rectangle = new Rectangle(
e.X <= _startingPoint.X ? e.X : _startingPoint.X,
e.Y <= _startingPoint.Y ? e.Y : _startingPoint.Y,
_startingPoint.X - e.X <= 0 ? _startingPoint.X - e.X : _startingPoint.X - e.X,
_startingPoint.Y - e.Y <= 0 ? e.Y - _startingPoint.Y : _startingPoint.Y - e.Y);
}
}
_isDrawing = false;
Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
using (Pen pen = new Pen(Color.Red, 2))
{
pen.DashStyle = DashStyle.Dash;
pe.Graphics.DrawRectangle(pen, _rectangle);
}
}
public void CropImage()
{
Bitmap bitmap = new Bitmap(_rectangle.Width, _rectangle.Height);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.DrawImage(this.Image, 0, 0, _rectangle, GraphicsUnit.Pixel);
}
Image = bitmap;
//Removing the rectangle after cropping.
_rectangle = new Rectangle(0, 0, 0, 0);
}
}
}
We can modify this control by adding nice to have features like
- Overlay while cropping.
- Drag and Re-size the selection Rectangle.
Happy Coding
How to use TaskDialog API in C#
The TaskDialog API replaces MessageBox. A message box is useful for prompting users for an acknowledgment, confirmation, or an answer to a yes or no question. Message boxes are popular because of the MessageBox function is convenient for developers to use. TaskDialog is the preferred API to use because it is similar to MessageBox but much more flexible. Previously, developers have created their own message box implementations when greater functionality was required. Unfortunately .Net framework doesn’t expose TaskDialog API directly; you need to use WIN32 api for it. Here is one Task dialog implementation in C#. Only limitation of Task Dialog API is it doesn’t supported by Windows operating systems less than Windows Vista.
Here is the API declarations.
[DllImport("comctl32.dll", CharSet = CharSet.Unicode, EntryPoint = "TaskDialog")]
static extern int TaskDialog(IntPtr hWndParent, IntPtr hInstance, String pszWindowTitle,
String pszMainInstruction, String pszContent, int dwCommonButtons,
IntPtr pszIcon, out TaskDialogResult pnButton);
//Dialog buttons
[Flags]
public enum TaskDialogButtons : int
{
Ok = 0x0001,
Cancel = 0x0008,
Yes = 0x0002,
No = 0x0004,
Retry = 0x0010,
Close = 0x0020
}
//Dialog Results
[Flags]
public enum TaskDialogResult : int
{
IDOK = 1,
IDCANCEL = 2,
IDRETRY = 4,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
NONE = 0
}
//Dialog Icons
[Flags]
public enum TaskDialogIcon
{
Information = UInt16.MaxValue - 2,
Warning = UInt16.MaxValue,
Stop = UInt16.MaxValue - 1,
Question = 0,
SecurityWarning = UInt16.MaxValue - 5,
SecurityError = UInt16.MaxValue - 6,
SecuritySuccess = UInt16.MaxValue - 7,
SecurityShield = UInt16.MaxValue - 3,
SecurityShieldBlue = UInt16.MaxValue - 4,
SecurityShieldGray = UInt16.MaxValue - 8
}
And here is my TaskDialog wrapper function.
public static TaskDialogResult Show(IntPtr handle, string messageTitle, string mainTitle,
string mainContent, TaskDialogButtons taskDialogButtons, TaskDialogIcon taskDialogIcon)
{
TaskDialogResult buttonClicked = TaskDialogResult.IDCANCEL;
TaskDialog(handle, IntPtr.Zero, messageTitle, mainTitle, mainContent,
(int)taskDialogButtons, (IntPtr)(int)taskDialogIcon, out buttonClicked);
return buttonClicked;
}
And here is the screen shot of Task Dialog running in my Windows 7 machine.
Creating color picker application in C#
Yesterday I modified my blog’s theme. That time I thought about writing an application to pick color from any where in the screen like web page or application. I know there are some applications already out there in the market to do this. Yet again I thought of writing one.
The main challenges on the implementation of me
- How to get the mouse position when the mouse pointer is out of the Form. – I found one solution with GetCursorPos() WIN32 API function.
Point p = new Point(); GetCursorPos(ref p);
- How to monitor the position of the Mouse Pointer – I couldn’t find easy solution for this(There is some solution like Hooking the mouse). So I added a timer control into the form, and in the Tick Event I called the GetCursorPos() function.
- The major challenge was Getting the color from the position, I searched net, and I found solution using GetPixel() API function.
IntPtr hdc = GetDC(IntPtr.Zero); uint pixel = GetPixel(hdc, currentPoint.X, currentPoint.Y); ReleaseDC(IntPtr.Zero, hdc);
- The last challenge was to keep the Form always on top of other forms. Again I found solution using SetWindowPos() method.
And here is the screenshot of color picker.
You can download ColorPicker source from ColorPicker – Source Files


