Saturday , 27 July 2024
HOT

Convert chuỗi string thành hình ảnh trong asp.net

Bài viết này hướng dẫn các bạn chuyển chuỗi string thành hình ảnh, Cái này rất tốt để tránh các Spider vào lấy email người dùng để đi spam

1. Tạo 1 file TextImage.ashx trong Project

2. Copy đoạn code sau:

using System;
using System.Web;
using System.Drawing;
using System.IO;
 
public class GenerateImage : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        string strDisplay = "abc@abc.com";
        Bitmap bmpOut = new Bitmap(200, 50);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.FillRectangle(Brushes.Black,0,0,200,50);
        g.DrawString(strDisplay, new Font("Verdana", 18), new SolidBrush(Color.White), 0, 0);     
        MemoryStream ms = new MemoryStream();      
        bmpOut.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
        byte[] bmpBytes = ms.GetBuffer();
        bmpOut.Dispose();
        ms.Close();
        context.Response.BinaryWrite(bmpBytes);
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Chúc bạn thành công

N g u ồ n : m e o t o m . n e t

Leave a Reply

Your email address will not be published. Required fields are marked *

*