开发者

asp.net - Generated bitmap to img tag src

I am rolling my own captcha, since recaptcha is prooving to be a bit complex for a client's visitors. I have the following code:

private Bitmap generateCaptchaNumbers()
    {
        Random num1 = new Random();
        Random num2 = new Random();

        int numQ1;
        int numQ2;
        string QString;

        numQ1 = num1.Next(10, 15);
        numQ2 = num2.Next(10, 15);

        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        _answer = numQ1 + numQ2;
        Bitmap bmp = new Bitmap(85, 35);
        Graphics gfx = Graphics.FromImage(bmp);
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);
        Rectangle rect = new Rectangle(0, 0, 100, 50);

        gfx.FillRectangle(Brushes.White, rect);
        g开发者_高级运维fx.DrawString(QString, font, Brushes.Blue, 0, 0);

        return bmp;
    }

How would I go about showing the generated bmp inside my registration usercontrol?

I would rather not need to save the generated bmp to disk, if possible.


You have to create a HttpHandler implementing the IHttpHandler and return the binary inside the ProcessRequest:

context.Response.Clear();
context.Response.ContentType = "image/jpeg";
MemoryStream stream = new MemoryStream();
Bitmap bitmap = generateCaptchaNumbers();
bitmap.Save(stream, ImageFormat.Jpeg);
context.Response.BinaryWrite(stream.GetBuffer());

UPDATE: Follow this link to create and deploy a custom HttpHandler: http://support.microsoft.com/kb/308001


You'll need to convert the bitmap to a gif, jpg, or png and then return that image to the http response. Also set the response's content type to image/gif (or jpg, png) to match the type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜