Friday, September 9, 2011

Convert byte array to image in ASP.NET

There are several cases you want to convert byte array to image. For example, if you have image data in your database, your image will be byte array. Another example is you might to want to draw picture on th fly in your memory and send the image to web browser. This article shows how to convert the binary data to actual image in ASP.NET.

1) First, create a new ASP.NET webpage(.aspx) and remove all content except first line as follows. We will send image directly from code-behind code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestWeb1.WebForm1" %>

2) In code-behind page, call CreateImage method in Page_Load. This means when the aspx page is loaded, the image will be sent to web browser.

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

namespace TestWeb1
{
   public partial class WebForm1 : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         this.CreateImage();
      }

      protected void CreateImage()
      {
         int width = 100;
         int height = 100;
         Bitmap image = new Bitmap(width, height);
         Graphics g = Graphics.FromImage(image);

         try
         {
            // Draw something
            for (int i = 0; i < height/2; i+=4)
            {
               g.DrawRectangle(new Pen(Color.Red), i, i, image.Width - 1, image.Height - 1);
            }

            // Save it to memory in image format
            MemoryStream mem = new MemoryStream();
            image.Save(mem, System.Drawing.Imaging.ImageFormat.Gif);

            // Send byte array
            Response.ClearContent();
            Response.ContentType = "image/gif";
            Response.BinaryWrite(mem.ToArray());
            Response.End();
         }
         finally
         {
            g.Dispose();
            image.Dispose();
         }
      }
   }
}
In CreateImage() method, you create empty Bitmap image (100x100 in this example) and draw some rectangles by using graphics object. Once drawing is done, save the bitmap image to memory with specific image format. The example above (image.Save() method) shows that bitmap image is saved into memory in GIF format. Once formatted image is in memory, you can convert it to byte array. To send data to web browser, clear all content in Response object and set ContentType to specific image type (image/gif in this case). Then The byte array is sent to web browser by using Response.BinaryWrite(). When everything is done, call Response.End() and finish the work.

3) In your another web page, set <img> src attribe to the webpage created in step (1).

<img src="WebForm1.aspx" />
Since image is an independent web object, imageloading can be done separately by this way.

No comments:

Post a Comment