Cách xuất ảnh từ file aspx C#

Xuất ảnh từ file aspx giúp bạn tạo url ảnh đẹp hơn, và xử lý 1 số nghiệp vụ ngầm về email marketing.

1. Tại sao cần biết cách xuất ảnh từ aspx C#

Sử dụng ảnh ảnh lấy từ cơ sở dữ liệu

Sử dụng ảnh theo url tự tạo

2. Cách xuất ảnh từ một trang ASP.NET Web Forms (ASPX) sử dụng C#

Có thể được thực hiện theo nhiều cách tùy vào nghiệp vụ cần xử lý, dưới đây là một số cách code aspx C# để xuất ảnh từ ASPX:

Xuất ảnh từ đường dẫn file:

Nếu bạn có file ảnh trên máy chủ, bạn có thể trả về file ảnh trực tiếp từ server.
Code-behind (C#)

protected void Page_Load(object sender, EventArgs e)
{
    string imagePath = Server.MapPath("~/images/sample.jpg"); // Đường dẫn ảnh trên server
    Response.ContentType = "image/jpeg"; // Kiểu nội dung ảnh
    Response.WriteFile(imagePath); // Ghi nội dung file ảnh ra response
    Response.End(); // Kết thúc response
}

ASPX

<img src="DisplayImage.aspx" alt="Sample Image" />

Xuất ảnh từ byte array (database hoặc memory)

Nếu ảnh được lưu trong cơ sở dữ liệu hoặc dưới dạng byte[], bạn có thể sử dụng đoạn mã sau:
Code-behind (C#)

protected void Page_Load(object sender, EventArgs e)
{
    byte[] imageData = GetImageFromDatabase(); // Giả sử hàm này trả về byte[]
    if (imageData != null)
    {
        Response.ContentType = "image/png"; // Định dạng ảnh (jpeg, png, gif, v.v.)
        Response.BinaryWrite(imageData); // Ghi mảng byte ra response
        Response.End();
    }
}

// Ví dụ giả lập hàm lấy ảnh từ database
private byte[] GetImageFromDatabase()
{
    // Lấy ảnh từ CSDL
    return System.IO.File.ReadAllBytes(Server.MapPath("~/images/sample.png")); // Giả lập ảnh
}

ASPX

<img src="DisplayImage.aspx" alt="Sample Image" />

Xuất ảnh được tạo động từ GDI+

Bạn có thể tạo ảnh động bằng cách sử dụng GDI+ (System.Drawing).
Code-behind (C#)

protected void Page_Load(object sender, EventArgs e)
{
    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(200, 100))
    {
        using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
        {
            graphics.Clear(System.Drawing.Color.White);
            graphics.DrawString("Hello ASP.NET", new System.Drawing.Font("Arial", 16),
                                System.Drawing.Brushes.Black, new System.Drawing.PointF(10, 40));

            Response.ContentType = "image/png";
            bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
}

ASPX

<img src="DynamicImage.aspx" alt="Dynamic Image" />

Xuất ảnh qua URL với tham số

Bạn có thể tạo đường dẫn động để xuất ảnh theo ID hoặc tham số.
Code-behind (C#)

protected void Page_Load(object sender, EventArgs e)
{
    string imageId = Request.QueryString["id"];
    if (!string.IsNullOrEmpty(imageId))
    {
        // Lấy đường dẫn hoặc byte ảnh từ id
        string imagePath = Server.MapPath($"~/images/{imageId}.jpg");
        Response.ContentType = "image/jpeg";
        Response.WriteFile(imagePath);
        Response.End();
    }
}

ASPX

<img src="DisplayImage.aspx?id=sample" alt="Dynamic Image by ID" />

Xuất ảnh từ file aspx giúp bạn tạo url ảnh đẹp hơn, và xử lý 1 số nghiệp vụ ngầm về email marketing.