Archive

Posts Tagged ‘Drawing’

Color Picker Dropdown using C#

October 15th, 2009 Anuraj P No comments

While playing around one of hobby project, I found there is a nice color picker dropdown available in WordPad, for setting the font color. I was using Windows

Color Dialog. So I thought of implementing a WordPad like color picker. And I think I almost readed my goal. I need to try this in the Toolstrip dropdown too.

//On the Form load I am loading the colors to the Dropdown.
//You can also bind the p to the Dropdown.
Type t = typeof(Color);
PropertyInfo[] p = t.GetProperties();
foreach (PropertyInfo item in p)
{
    if (item.PropertyType.FullName.Equals("System.Drawing.Color", StringComparison.CurrentCultureIgnoreCase))
    {
        this.comboBox1.Items.Add(item.Name);
    }
}

And I set the Dropdown’s DrawMode property to “OwnerDrawFixed”. And in the DrawItem event of the Dropdown I wrote the code.

if (e.Index != -1)
{
    e.DrawBackground();
    e.Graphics.FillRectangle(GetCurrentBrush(comboBox1.Items[e.Index].ToString()), e.Bounds);
    Font f = comboBox1.Font;
    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), f, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
    e.DrawFocusRectangle();
}

And the GetCurrentBrush() function returns the Brush for painting the rectangle. You can write the code in the DrawItem event too, but initialy I thought about setting the font color using the same color. But later that idea changed.

private Brush GetCurrentBrush(string colorName)
{
    return new SolidBrush(Color.FromName(colorName));
}

One issue I found in this code is, for black color, I can’t see the color name. And here is the screenshot of Color Picker Dropdown running on my machine.

Color Picker Dropdown screenshot

Color Picker Dropdown screenshot

Convert Image to Icon using C#

September 30th, 2009 Anuraj P 6 comments

Sometimes we will get nice Images from Web as Icons. But we can’t use these Images as application icons in .Net, because the .Net supports *.ico(Icon) format only. This code will convert an Image to Icon using C#. It is written .Net Framework 3.5, but it should work in .Net 2.0. It supports Images upto size 128×128. And supports various image formats(*.jpg,*.gif, *.png. *.bmp).

using System;
using System.Drawing;
using System.IO;

string fileName, newFileName;
fileName = "C:\Sample.jpg";
newFileName = Path.ChangeExtension(fileName, ".ico");
using (Bitmap bitmap = Image.FromFile(fileName, true) as Bitmap)
{
    using (Icon icon = Icon.FromHandle(bitmap.GetHicon()))
    {
        using (Stream imageFile = File.Create(newFileName))
        {
            icon.Save(imageFile);
            Console.WriteLine("Converted - {0}", newFileName);
        }
    }
}

Code it pretty self explanatory. Let me know if you have faced any issues.

Captcha using ASP.Net and C#

September 15th, 2009 Anuraj P 4 comments

Few days back, I got some question related to Captcha (security mechanism, which helps web masters to avoid spam) in a Forum. So I thought of implementing one. I got few nice scripts in Code Project, its a simple implementation, no too much logic and not too complex to understand. Also I am using an HTTP Handler instead of ASPX Page, for the implementation.

using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb))
        {
            using (Graphics g = Graphics.FromImage(b))
            {
                Rectangle rect = new Rectangle(0, 0, 149, 39);
                g.FillRectangle(Brushes.White, rect);

                // Create string to draw.
                Random r = new Random();
                int startIndex = r.Next(1, 5);
                int length = r.Next(5, 10);
                String drawString = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length);

                // Create font and brush.
                Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout);
                using (SolidBrush drawBrush = new SolidBrush(Color.Black))
                {
                    // Create point for upper-left corner of drawing.
                    PointF drawPoint = new PointF(15, 10);

                    // Draw string to screen.
                    g.DrawRectangle(new Pen(Color.Red, 0), rect);
                    g.DrawString(drawString, drawFont, drawBrush, drawPoint);
                }
                b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                context.Response.ContentType = "image/jpeg";
                context.Response.End();
            }
        }

I wrote the code in the Process Request event in HTTPHandler.
And to use this in your pages you can create an IMG tag with src attribute pointing to this.

<img src="myhandler.ashx" />

Note: Some time ASP.Net caches the image, so you may need to pass some GUID as querystring in the Handler.

Update: Sometime we may need to refresh the Captcha image, without post back, here is a simple javascript which will refresh the captcha image without post back.

<script type="text/javascript">
        function RefreshCaptcha() {
            var img = document.getElementById("imgCaptcha");
            img.src = "Handler.ashx?query=" + Math.random();
        }
</script>
<div>
<img src="Handler.ashx" id="imgCaptcha" />
<a href="#" onclick="javascript:RefreshCaptcha();">Refresh</a>
</div>

Here is the screenshot of web page using Captcha.

Captcha - Security Image using ASP.Net and C#

Captcha - Security Image using ASP.Net and C#

Loading Image from URL in Windows Forms

May 19th, 2009 Anuraj P 2 comments

Recently I got a chance to work on Windows Application, it is Twitter client using C#. In that I need to show some Image from a URL. I thought like Microsoft will provide some way to load Images from URL and I tried to do the same with “Image.FromFile” method. But it failed. :( Then I searched and found it will not supports Urls. So I developed an extention method for Image class, which will load from URL. I tried to Inherit from Image class, but that doesn’t work, it is not inheritable. :(

And here is the code

namespace dotnetthoughts
{
	public static class Utilities
	{
		public static Image FromURL(this Image image, string Url)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(),true);
		}
		public static Image FromURL(this Image image, string Url, string userName, string Password)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			request.Credentials = new NetworkCredential(userName, Password);
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(), true);
		}
	}
}

In the second method, I am accepting the Username and Password, so it can access protected Images too.

Implementation of this code

//If we don't put null, C Sharp compiler will not allows to compile the application
Image img = null;
this.pictureBox1.Image = img.FromURL(this.textBox1.Text);
Categories: .Net, .Net 3.0 / 3.5, WPF Tags: , , ,

Freehand drawing with .Net Windows forms

February 26th, 2009 Anuraj P No comments

Few days back, I got a requirement to implement Free Hand drawing in .Net. I searched a lot but I didn’t get any good solution, the one I found from code project was Invalidating the picture box every time. So today I got a solution, it not seems to be a perfect solution because Paint events occurs, we need to re-paint the whole lines again.

I am attaching the code here. I will update the post once I get some perfect solution for this.

 Private m_Drawing As Boolean = False
    Private m_List As List(Of Point) = Nothing
    Private Sub MyPic_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Left Then
            m_Drawing = True
        End If
    End Sub
    Private Sub MyPic_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseUp
        If m_Drawing AndAlso m_List IsNot Nothing Then
            If m_List.Count >= 2 Then
                MyPic.CreateGraphics.DrawLines(New Pen(Color.Blue, 1), m_List.ToArray())
            End If
            m_Drawing = False
            m_List.Clear()
        End If
    End Sub

    Private Sub MyPic_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyPic.MouseMove
        If m_List IsNot Nothing AndAlso m_Drawing Then
            m_List.Add(e.Location)
        End If
    End Sub
    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        m_List = New List(Of Point)
    End Sub

Code is pretty self explanatory. So I am not putting any comments ;)

Capture screen using C# and .Net 2.0

April 13th, 2007 Anuraj P No comments

Remember old BitBlt API, for capturing screens? Here is the solution from Microsoft on .Net framework 2.0. CopyFromScreen Method – Performs a bit-block transfer of color data from the screen to the drawing surface of the Graphics.

Rectangle region = new Rectangle(0, 0, SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);
using (Bitmap bitmap = new Bitmap(region.Width, region.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
using (Graphics bitmapGraphics = Graphics.FromImage(bitmap))
{
bitmapGraphics.CopyFromScreen(region.Left, region.Top, 0, 0, region.Size);
Clipboard.SetImage(bitmap);
}

It only works with .Net 2.0 and more.

I developed an Application, which hosted in Codeplex, called captureit., which is using this code for capturing desktop.

MSDN : http://msdn2.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx