imageComponent.NET - image processing .NET assemblies
Resize a uploaded image and store it to the database, then display it in ASP.NET

Introduction

This question has been asked by couple of my clients, so even it is only related to PhotoController a little, I would still like to add this here.

Database

First, let's suppose we have a database called [TestDB] and a table called [ImageStore]. You can create the table by using the following TSQL (the example was built to work with Microsoft SQL Server 2000:

   1:  CREATE TABLE [dbo].[ImageStore] (
   2:  [ImageID] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
   3:  [ImageData] [image] NULL ,
   4:  [ImageContentType] [varchar] (50) NULL ,
   5:  [ImageDescription] [varchar] (200) NULL ,
   6:  [ImageSize] [int] NULL 
   7:  ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
   8:   

The description of each field is:

ImageID - primary key
ImageData - stores the image binary data
ImageContentType - stores the image file type
ImageDescription - stores the description for this picture
ImageSize - stores the size of image

ASP.NET files

UploadImage.aspx

   1:  <%@ Page language="c#" Codebehind="UpLoadImage.aspx.cs" AutoEventWireup="false" Inherits="TestApp.UploadImage" %>
   2:       <HTML>
   3:       <title>Upload Image</title>
   4:       <BODY bgColor="#ffffff">
   5:       <FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">
   6:       <TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0" cellspacing="0" border="0">
   7:       <TR>
   8:            <TD>Upload file:</TD>
   9:            <TD>
  10:                 <INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="WIDTH:320px" ACCEPT="text/*" NAME="UP_FILE">
  11:            </TD>
  12:        </TR>
  13:        <TR>
  14:            <TD>Description:</TD>
  15:            <TD>
  16:                 <asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" MAINTAINSTATE="false" />
  17:            </TD>
  18:        </TR>
  19:        <TR>
  20:            <TD>
  21:                 <asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" MAINTAINSTATE="false" />
  22:            </TD>
  23:            <TD>
  24:                 <asp:Button RUNAT="server" WIDTH="239" ONCLICK="Button_Submit" TEXT="Upload Image" ID="Button1" NAME="Button1" />
  25:            </TD>
  26:        </TR>
  27:       </TABLE>
  28:       </FORM>
  29:       </BODY>
  30:       </HTML>
  31:   
  32:   

UploadImage.aspx.cs

This is the code-behind of the page above:

   1:  using System; 
   2:  using System.Web; 
   3:  using System.IO; 
   4:  using System.Data; 
   5:  using System.Data.SqlClient; 
   6:  using System.Web.UI; 
   7:  using System.Web.UI.WebControls; 
   8:  using System.Web.UI.HtmlControls; 
   9:  using IC.PhotoController;
  10:   
  11:  namespace TestApp 
  12:  { 
  13:      public class UploadImage : Page 
  14:      { 
  15:      protected HtmlInputFile UP_FILE; 
  16:      protected TextBox txtDescription; 
  17:      protected Label txtMessage;
  18:      protected System.Web.UI.WebControls.Button Button1; 
  19:      protected Int32 FileLength = 0;
  20:   
  21:      private void InitializeComponent()
  22:      {
  23:      // do nothing
  24:      }
  25:   
  26:      protected void Button_Submit(System.Object sender, System.EventArgs e) 
  27:      { 
  28:          // used to read the properties of image
  29:          HttpPostedFile UpFile = UP_FILE.PostedFile; 
  30:   
  31:          // File size length
  32:          FileLength = UpFile.ContentLength;
  33:          try 
  34:          { 
  35:              if (FileLength == 0) 
  36:              {
  37:                  txtMessage.Text = "<b>Please choose a file to upload</b>"; 
  38:              } 
  39:              else 
  40:              { 
  41:                  Byte[] FileByteArray = new Byte[FileLength]; 
  42:                  Stream StreamObject = UpFile.InputStream; 
  43:                  StreamObject.Read(FileByteArray,0,FileLength); 
  44:   
  45:                  // Creates a MemoryStream object from the Byte[]
  46:                  MemoryStream mStream =new MemoryStream(FileByteArray);
  47:   
  48:                  // Creates an Image object from the MemoryStream
  49:                  // Because PhotoController only returns Image, we have to have one.
  50:                  System.Drawing.Image image = System.Drawing.Image.FromStream(mStream);
  51:   
  52:                  // Initializes the PhotoController from the Image object
  53:                  IC.PhotoController.Controller objPc = new IC.PhotoController.Controller(image);
  54:   
  55:                  // Resize the image to half size, please refer to Resize method with a float parameter
  56:                  image = objPc.Resize(0.5f);
  57:   
  58:                  // Release PhotoController
  59:                  objPc.Dispose();
  60:   
  61:                  // We need a new empty MemoryStream
  62:                  mStream.Close();
  63:                  mStream = new MemoryStream();
  64:   
  65:                  // Save the Image object into MemoryStream. Use Bmp format is a best choice.
  66:                  image.Save(mStream, System.Drawing.Imaging.ImageFormat.Bmp);
  67:   
  68:                  // retrieve the Byte[], used to save into DataBase
  69:                  FileByteArray = mStream.ToArray();
  70:   
  71:                  // Because mStream.Length returns long, be aware that if the uploaded file size is too large
  72:                  FileLength = (Int32) mStream.Length;
  73:   
  74:                  // Release the MemoeryStream resource
  75:                  mStream.Close();
  76:   
  77:                  // connect to local SQL Server, no comment for this part
  78:                  SqlConnection sqlConn = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;"); 
  79:                  String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)"; 
  80:                  SqlCommand sqlCmd= new SqlCommand(SqlCmd, sqlConn); 
  81:                  sqlCmd.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray; 
  82:                  sqlCmd.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType; 
  83:                  sqlCmd.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = txtDescription.Text; 
  84:                  sqlCmd.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength; 
  85:                  sqlConn.Open(); 
  86:                  sqlCmd.ExecuteNonQuery(); 
  87:                  sqlConn.Close(); 
  88:                  sqlCmd.Dispose(); 
  89:                  txtMessage.Text = "<p><b>You have uploaded your image successfully!</b>";
  90:              } 
  91:          } 
  92:          catch (Exception ex) 
  93:          { 
  94:              txtMessage.Text = ex.Message.ToString(); 
  95:          }
  96:      }
  97:      }
  98:  } 

ReadImage.aspx

We need a page to grab the database data and render it as an image. This page will accomplish this job. We only need to put the logic in the code-behind.

   1:  <%@ Page language="c#" Codebehind="ReadImage.aspx.cs" AutoEventWireup="false" Inherits="TestApp.ReadImage" %>

ReadImage.aspx.cs

   1:  using System;
   2:  using System.Collections;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Web;
   7:  using System.Web.SessionState;
   8:  using System.Web.UI;
   9:  using System.Web.UI.WebControls;
  10:  using System.Web.UI.HtmlControls;
  11:  using System.Data.SqlClient; 
  12:   
  13:  namespace TestApp
  14:  {
  15:      public class ReadImage : System.Web.UI.Page
  16:      {
  17:          private void Page_Load(object sender, System.EventArgs e)
  18:          {
  19:              int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]); 
  20:              SqlConnection sqlConn= new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;"); 
  21:              String strCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID"; 
  22:              SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn); 
  23:              sqlCmd.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID; 
  24:              sqlConn.Open(); 
  25:              SqlDataReader SqlReader = sqlCmd.ExecuteReader(); 
  26:              SqlReader.Read(); 
  27:              Response.ContentType = (string)SqlReader["ImageContentType"];
  28:              Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]); 
  29:              Response.End(); 
  30:              sqlConn.Close(); 
  31:              sqlCmd.Dispose(); 
  32:          }
  33:   
  34:          override protected void OnInit(EventArgs e)
  35:          {
  36:              InitializeComponent();
  37:              base.OnInit(e);
  38:          }
  39:   
  40:          private void InitializeComponent()
  41:          { 
  42:              this.Load += new System.EventHandler(this.Page_Load);
  43:          }
  44:      }
  45:  }
  46:   

ShowImage.html

Now you need a container (page) to display the image:

   1:  <img src="ReadImage.aspx?ImgID=1"> 

[Back to Top]
Comments

If you feel this page can be improved or has any mistake, please enter your valuable opinion here. Or if you cannot find the information you are after, feel free to suggest a subject too. I appreciate any voice.

Your Name:
  
Your Email Address:
  
Comments: