Captcha image - ASP.NET - c#

I'm in the process of making my own Captcha check on my website.
Everything's working, except I need some blurryness/effects on my text that's not viewable by a webcrawler etc.
Some of the code used to generate the text on the image:
Bitmap BitMap = new Bitmap(#"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");
Graphics g = Graphics.FromImage(BitMap);
g.DrawString(""+RandomNumberString+"", new Font("Tahoma", 40), Brushes.Khaki, new PointF(1, 1));
pictureBox1.Image = BitMap;
Example:
What can I do to get my effects/blurryness on my text?
Thank you!

Why roll out your own captcha when reCAPTCHA is free, accessible (through the audio option, making it usable for people with visual issues) and at the same time helps digitize various publications? There's even a .NET implementation.
Edit:
Seeing how it's for fun, having a look at "An ASP.NET Framework for Human Interactive Proofs" might give you some good ideas. Especially the ImageHipChallenge as it includes image distortion code examples.
For example:
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int newX = (int)(x + (distortion * Math.Sin(Math.PI * y / 64.0)));
int newY = (int)(y + (distortion * Math.Cos(Math.PI * x / 64.0)));
if (newX < 0 || newX >= width) newX = 0;
if (newY < 0 || newY >= height) newY = 0;
b.SetPixel(x, y, copy.GetPixel(newX, newY));
}
}
Which will move the pixels in a wave like fashion. Such as in the second word of your example.

Have a look at this tutorial. There you will find a code example on how to create a CAPTCHA using C# and the DrawString method.
Hope, this helps.

I've used this for about 5 years and it doesn't involve any integration with horrid 3rd party APIs.
http://www.codeproject.com/KB/aspnet/CaptchaImage.aspx

protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
LoadCaptcha();[![enter image description here][1]][1]
}
}
public void LoadCaptcha()
{
try
{
Bitmap objBitmap = new Bitmap(130, 60);
Graphics objGraphics = Graphics.FromImage(objBitmap);
objGraphics.Clear(Color.White);
Random objRandom = new Random();
objGraphics.DrawLine(Pens.Black, objRandom.Next(0, 50), objRandom.Next(10, 30), objRandom.Next(0, 200), objRandom.Next(0, 50));
objGraphics.DrawRectangle(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(0, 20), objRandom.Next(50, 80), objRandom.Next(0, 20));
objGraphics.DrawLine(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(10, 50), objRandom.Next(100, 200), objRandom.Next(0, 80));
Brush objBrush =
default(Brush);
//create background style
HatchStyle[] aHatchStyles = new HatchStyle[]
{
HatchStyle.BackwardDiagonal, HatchStyle.Cross, HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal, HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical,
HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross, HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, HatchStyle.LargeConfetti, HatchStyle.LargeGrid, HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal
};
////create rectangular area
RectangleF oRectangleF = new RectangleF(0, 0, 300, 300);
objBrush = new HatchBrush(aHatchStyles[objRandom.Next(aHatchStyles.Length - 3)], Color.FromArgb((objRandom.Next(100, 255)), (objRandom.Next(100, 255)), (objRandom.Next(100, 255))), Color.White);
objGraphics.FillRectangle(objBrush, oRectangleF);
//Generate the image for captcha
string captchaText = string.Format("{0:X}", objRandom.Next(1000000, 9999999));
//add the captcha value in session
Session["CaptchaVerify"] = captchaText;
Font objFont = new Font("Courier New", 15, FontStyle.Bold);
//Draw the image for captcha
objGraphics.DrawString(captchaText, objFont, Brushes.Black, 20, 20);
// objBitmap.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);
byte[] _bytes;
using (MemoryStream ms = new MemoryStream())
{
objBitmap.Save(ms, ImageFormat.Bmp);
_bytes = ms.ToArray();
}
imgcaptcha.ImageUrl = "data:image;base64," + Convert.ToBase64String(_bytes);
ImageCapchaSubmit.ImageUrl = "data:image;base64," + Convert.ToBase64String(_bytes);
}
catch (Exception)
{
}
}

Related

Create a Bitmap image to show an hour worked using c#

I am trying to make a Bitmap image to represent a block of one hour and show red as worked time and white as non-worked showing in periods of 10 minutes intervals. I am trying to get the result to look like below:
Any help or guidance would be greater appreciated. In the code below Tuple<int,DateTime>> the int is time block example 0,1,2,3.....21,22,23,24 and DateTime will hold the time worked.
public void DrawPeriod(IGrouping<int, Tuple<int, DateTime>> worked)
{
var bitmap = new Bitmap(640, 480);
for (var x = 0; x < bitmap.Width; x++)
{
for (var y = 0; y < bitmap.Height; y++)
{
bitmap.SetPixel(x, y, Color.Red);
}
}
bitmap.Save("worked.bmp");
}
Sorry I can't give a sample with the data you needed. But you can do it something like this. This can be achieved by using System.Drawing.Graphics.
var sampleData = new int[] { 1, 2, 3, 13, 4, 5, 6, 12, 7, 8, 9 };
var bitmapHeight = 250;
var barWidth = 50;
var bitmap = new Bitmap(sampleData.Length * barWidth, bitmapHeight);
int currentX = 1;
foreach (var item in sampleData)
{
var result = item % 2;
Brush brush;
if (result == 0)
{
brush = Brushes.Red;
}
else
{
brush = Brushes.White;
}
using (Graphics graphics = Graphics.FromImage(bitmap))
{
var rectangle = new Rectangle(currentX, 0, barWidth, bitmapHeight);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.FillRectangle(brush, rectangle);
// Set Text
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
graphics.DrawString(item.ToString(), drawFont, drawBrush, currentX + 15, bitmapHeight / 2);
}
currentX = currentX + 50;
}
// Border
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.DrawRectangle(new Pen(Brushes.Black, 5), new Rectangle(0, 0, bitmap.Width, bitmap.Height));
}
bitmap.Save(FileName);
Sample Output

I need to draw 10000 Points in a Panel without blocking the UI

I need to draw 10000 Points in a Panel without blocking the UI. I am using C#.
Currently I am doing the drawing in the panel Paint event. How can I do this without blocking the UI. I already tried doing the "painting" on a separate Thread but failed to succeed
private void Panel1Paint(object sender, PaintEventArgs paintEventArgs)
{
var g = paintEventArgs.Graphics;
g.DrawLine(new Pen(Color.Black),
new Point(0, panel1.Width / 2),
new Point(panel1.Height, panel1.Width / 2));
g.DrawLine(new Pen(Color.Black),
new Point(panel1.Width / 2, 0),
new Point(panel1.Width / 2, panel1.Height));
for (int i = 0; i < centres.Length; i++)
{
g.FillEllipse(new SolidBrush(colors[i]), centres[i].X, centres[i].Y, 10, 10);
Console.Out.WriteLine(centres[i].ToCart());
}
for (int i = 0; i < 10000; i++)
{
int zona = r.Next(0, 3);
double p_gauss, p_rand;
int new_x;
int new_y;
do
{
new_x = r.Next(0, 400);
p_gauss = Gauss(new_x, centres[zona].X, s[zona].X);
p_rand = r.NextDouble();
} while (p_gauss < p_rand);
do
{
new_y = r.Next(0, 400);
p_gauss = Gauss(new_y, centres[zona].Y, s[zona].Y);
p_rand = r.NextDouble();
} while (p_gauss < p_rand);
g.DrawEllipse(new Pen(colors[zona], 2), new_x, new_y, 1, 1);
}
}
Do your painting on a Bitmap, in a Thread. Make the finished bitmap available to your Form and let the Paint event draw the whole bitmap at once.

Adding images to pictureBox

I'm writing a simple game - snake. I would like to have background and my snake on it. I think that the best way is use two pictureBox (one with background and second - transparent with snake on it).
This is a good way? And how can I put several small images (snake's segments) on one picture box in different places (just copy pixel's (one after one) from image to pictureBox or maybe there is fastest way - putting all image in correct place)? I have pictureBox with background (parent) and and another, transparent (child) on it now.
The result should be look something like that:
I've made something like that (thanks to #dotTutorials), but my snake's segments are a little bit bigger than original images and cookie is smaller. Where can be a problem?
Drawing Code:
public Bitmap PrinPlayground()
{
char[,] tempPitch = play.getPitch();
Graphics g = pb2.CreateGraphics();
Bitmap bitmap = new Bitmap(512, 512);
Graphics BBG = Graphics.FromImage(bitmap);
Bitmap head = CookieSnake.Properties.Resources.head;
Bitmap body01 = CookieSnake.Properties.Resources.body01;
Bitmap tail = CookieSnake.Properties.Resources.tail;
Bitmap cookie = CookieSnake.Properties.Resources.cookie;
BBG.Clear(Color.Transparent);
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++)
{
if (tempPitch[i, j] == 'H')
{
BBG.DrawImage(head, new Point(32*j, 32*i));
}
else if (tempPitch[i, j] == 'B')
{
BBG.DrawImage(body01, new Point(32*j, 32*i));
}
else if (tempPitch[i, j] == 'T')
{
BBG.DrawImage(tail, new Point(32 * j, 32 * i));
}
else if (tempPitch[i, j] == 'C')
{
BBG.DrawImage(cookie, new Point(32 * j, 32 * i));
}
}
g.DrawImage(bitmap, new Point(0,0));
return bitmap;
}
Result:
The best way to achieve this is definitely to use the 'Graphics' class. Please look further into the GDI, and the namespace System.Drawing.
If you want to use a Picturebox representing the game space, you can easily implement graphics to a picturebox as well, by calling the member CreateGraphics.
I hope this helps you! :)
Please notice that when you get into serious game development, you'll have to find a better alternative than GDI. I personally prefer the XNA library
Example usage of GDI [This written fast, and should not be copy - pasted. However; It is a good point of origin :)]
Graphics g = pictureBox1.CreateGraphics();
Bitmap BB = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics BBG = Graphics.FromImage(BB);
Bitmap Background = (Bitmap)Bitmap.FromFile("BackgroundPicture.png");
Bitmap Head = (Bitmap)Bitmap.FromFile("SnakeHead.png");
Bitmap Tail = (Bitmap)Bitmap.FromFile("SnakeTail.png");
Point snakeLocation = new Point((BB.Width / 2) - (Head.Width / 2), (BB.Height / 2) - (Head.Height / 2));
while (true) {
#region Update
// update method here!
snakeLocation.X += 1;
#endregion
#region Draw
BBG.Clear(Color.CornflowerBlue);
BBG.DrawImage(Background, new Point(0, 0));
BBG.DrawImage(Head, snakeLocation);
BBG.DrawImage(Tail, new Point(snakeLocation.X - Head.Width, snakeLocation.Y));
g.DrawImage(BB, new Point(0, 0)); // draw to screen
#endregion
}
UPDATE: The DrawImage method also accepts a RectangleF input. A RectangleF consits of 4 datatypes, float X, float Y, float Width and float Height.
With a RectangleF you can easily specify the size of the drawn image. Take a look at the code below:
public Bitmap PrinPlayground() {
char[,] tempPitch = play.getPitch();
Graphics g = pb2.CreateGraphics();
Bitmap bitmap = new Bitmap(512, 512);
Graphics BBG = Graphics.FromImage(bitmap);
Bitmap head = CookieSnake.Properties.Resources.head;
Bitmap body01 = CookieSnake.Properties.Resources.body01;
Bitmap tail = CookieSnake.Properties.Resources.tail;
Bitmap cookie = CookieSnake.Properties.Resources.cookie;
BBG.Clear(Color.Transparent);
for (int i = 0; i < 16; i++)
for (int j = 0; j < 16; j++) {
if (tempPitch[i, j] == 'H') {
BBG.DrawImage(head, new RectangleF(new Point(32 * j, 32 * i), new SizeF(/*Adjust the size after your pleasure*/32, 32)));
}
else if (tempPitch[i, j] == 'B') {
BBG.DrawImage(body01, new RectangleF(new Point(32 * j, 32 * i), new SizeF(32, 32)));
}
else if (tempPitch[i, j] == 'T') {
BBG.DrawImage(tail, new RectangleF(new Point(32 * j, 32 * i), new SizeF(32, 32)));
}
else if (tempPitch[i, j] == 'C') {
BBG.DrawImage(cookie, new RectangleF(new Point(32 * j, 32 * i), new SizeF(/*Half the size of the head [Adjust after your needs!]*/32 / 2, 32 / 2)));
}
}
g.DrawImage(bitmap, new Point(0, 0));
return bitmap;
}
}

Animated bar in progress bar winform

I'm writing an extended progress bar control at present, 100% open source and I've created some basic styles with gradients and solid colours.
One of the options I wanted to add was animation to the bar, prety much like the windows 7 and vista green progress bar. So I need to add a moving "Glow" to the % bar, however my attempt at this looks terrible.
My method is to draw an ellipse with set size and move it's x position until it reaches the end were the animation starts again.
First of does anyone have nay links or code to help me achieve the current windows 7 glow effect using GDI or some similar method?
I have several other animations that will also be added the the bar hence the GDI.
private void renderAnimation(PaintEventArgs e)
{
if (this.AnimType == animoptions.Halo)
{
Rectangle rec = e.ClipRectangle;
Rectangle glow = new Rectangle();
//SolidBrush brush = new SolidBrush(Color.FromArgb(100, Color.White));
//int offset = (int)(rec.Width * ((double)Value / Maximum)) - 4;
int offset = (int)(rec.Width / Maximum) * Value;
if (this.animxoffset > offset)
{
this.animxoffset = 0;
}
glow.Height = rec.Height - 4;
if (this.animxoffset + glow.X > offset)
{
glow.Width = offset - (this.animxoffset + 50);
}
else
{
glow.Width = 50;
}
glow.X = this.animxoffset;
LinearGradientBrush brush = new LinearGradientBrush(glow, Color.FromArgb(0, Color.White), Color.FromArgb(100, Color.White), LinearGradientMode.Horizontal);
e.Graphics.FillEllipse(brush, this.animxoffset, 2, glow.Width, glow.Height);
brush.Dispose();
string temp = offset.ToString();
e.Graphics.DrawString(temp + " : " + glow.X.ToString(), DefaultFont, Brushes.Black, 2, 2);
animTimer = new System.Timers.Timer();
animTimer.Interval = 10;
animTimer.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
animTimer.Start();
}
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.animTimer.Stop();
this.animxoffset += 2;
Invalidate();
}
This is just an example glow iterating through a pen array.
You could also use a transparent image (although it could have a performance impact).
Pen[] gradient = { new Pen(Color.FromArgb(255, 200, 200, 255)), new Pen(Color.FromArgb(150, 200, 200, 255)), new Pen(Color.FromArgb(100, 200, 200, 255)) };
int x = 20;
int y = 20;
int sizex = 200;
int sizey = 10;
int value = 25;
//draw progress bar basic outline (position - 1 to compensate for the outline)
e.Graphics.DrawRectangle(Pens.Black, new Rectangle(x-1, y-1, sizex, sizey));
//draw the percentage done
e.Graphics.FillRectangle(Brushes.AliceBlue, new Rectangle(x, y, (sizex/100)*value, sizey));
//to add the glow effect just add lines around the area you want to glow.
for (int i = 0; i < gradient.Length; i++)
{
e.Graphics.DrawRectangle(gradient[i], new Rectangle(x - (i + 1), y - (i + 1), (sizex / 100) * value + (2 * i), sizey + (2 * i)));
}

Improving performance of drawing Tiled bitmaps in wpf

I'm looking for a way to improve the performance of some drawing I am doing. Currently it is a 32x32 grid of tiles that I am drawing. Using the following code to draw onto the drawing context
for (int x = startX; x < endX; x++)
{
for (int y = startY; y < endY; y++)
{
dg.Children.Add(
new ImageDrawing(_mapTiles[GameWorldObject.GameMap[x, y].GraphicsTile.TileStartPoint],
new Rect(CountX * 8, CountY * 8, 8, 8)
));
dg.Children.Add(
new GeometryDrawing(
null,
new Pen(
new SolidColorBrush(
Color.FromRgb(255, 0, 20)), .3),
new RectangleGeometry(
new Rect(CountX * 8, CountY * 8, 8, 8)
)
)
);
CountY++;
}
CountY = 0;
CountX++;
}
dc.DrawDrawing(dg);
The Image I am drawing is a CachedBitmap. Even using a CachedBitmap, I still have a delay of about a half second each time I need to redraw the Canvas.
Not sure if there is a more performant way to handle drawing to this grid. Eventually I want to expand control to function as a mini-map, so I need to keep that in mind.
Also, I tried previously to just draw each bitmap directly to the drawing context but that seems a bit slower.
I added DrawingGroup.Freeze() before drawing, and it seemed to help with the performance.
If it's mostly static minimap draw it into an Image, and draw that image. Or you can do a big image, where you draw the whole map into it, and just draw the current visible part of it.
Edit: And maybe this blog post worth a check, whether you are drawing it with software or hardware acceleration on.
Here's a example using WriteableBitmap, the performance of this is mainly related to the size of the whole map whereas your original method is more dependent on the amount of tiles. You could alter it to have an alpha-blended border between the tiles but leaving a gap between them would be easier and more performant. You won't need the code randomising the tiles but you should have some dirty flag so you only redraw the bitmap when its changed.
You may also want to look my answer and the others to this question. That said you don't have as many items and 32x32 using your method wasn't slow for me.
<local:Map x:Name="map" />
<RepeatButton Click="Button_Click" Content="Change" />
private void Button_Click(object sender, RoutedEventArgs e)
{
map.seed++;
map.InvalidateVisual();
}
public class Map : FrameworkElement
{
private int[][] _mapTiles;
public Map()
{
_mapTiles = Directory.GetFiles(#"C:\Users\Public\Pictures\Sample Pictures", "*.jpg").Select(x =>
{
var b = new BitmapImage(new Uri(x));
var transform = new TransformedBitmap(b, new ScaleTransform((1.0 / b.PixelWidth)*tileSize,(1.0 / b.PixelHeight)*tileSize));
var conv = new FormatConvertedBitmap(transform, PixelFormats.Pbgra32, null, 0);
int[] data = new int[tileSize * tileSize];
conv.CopyPixels(data, tileSize * 4, 0);
return data;
}).ToArray();
bmp = new WriteableBitmap(w * tileSize, h * tileSize, 96, 96, PixelFormats.Pbgra32, null);
destData = new int[bmp.PixelWidth * bmp.PixelHeight];
}
const int w = 64, h = 64, tileSize = 8;
public int seed = 72141;
private int oldSeed = -1;
private WriteableBitmap bmp;
int[] destData;
protected override void OnRender(DrawingContext dc)
{
if(seed != oldSeed)
{
oldSeed = seed;
int startX = 0, endX = w;
int startY = 0, endY = h;
Random rnd = new Random(seed);
for(int x = startX; x < endX; x++)
{
for(int y = startY; y < endY; y++)
{
var tile = _mapTiles[rnd.Next(_mapTiles.Length)];
var rect = new Int32Rect(x * tileSize, y * tileSize, tileSize, tileSize);
for(int sourceY = 0; sourceY < tileSize; sourceY++)
{
int destY = ((rect.Y + sourceY) * (w * tileSize)) + rect.X;
Array.Copy(tile, sourceY * tileSize, destData, destY, tileSize);
}
}
}
bmp.WritePixels(new Int32Rect(0, 0, w * tileSize, h * tileSize), destData, w * tileSize * 4, 0);
}
dc.DrawImage(bmp,new Rect(0,0,w*tileSize,h*tileSize));
}
}

Categories

Resources