Knowledge Base > Resize Uploaded Image to Database
PhotoController 2.1
ContentsIndexHome
PreviousUpNext
Resize Uploaded Image to SQL Server Database

This article is going to show how to resize the uploaded picture file with PhotoController. Since a user asks me this question, and I do feel this is a popular question, I decide to publish my solution.

Firstly, assume there is a Database named [TestDB], and there is a table named [ImageStore] under it. Create this table with the following code:

CREATE TABLE [dbo].[ImageStore] (
[ImageID] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[ImageData] [image] NULL ,
[ImageContentType] [varchar] (50) NULL ,
[ImageDescription] [varchar] (200) NULL ,
[ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Field Description

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

Secondly, I write a simple project [TestApp], which has only three files - [UpLoadImage.aspx], [ReadImage.aspx], and [showimage.htm] . All codes will be shown in the following:

UpLoadImage.aspx

<%@ Page language="c#" Codebehind="UpLoadImage.aspx.cs" AutoEventWireup="false" Inherits="TestApp.UploadImage" %>
     <HTML>
     <title>Upload Image</title>
     <BODY bgColor="#ffffff">
     <FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">
     <TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0" cellspacing="0" border="0">
     <TR>
          <TD>Upload file:</TD>
          <TD>
               <INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="WIDTH:320px" ACCEPT="text/*" NAME="UP_FILE">
          </TD>
      </TR>
      <TR>
          <TD>Description:</TD>
          <TD>
               <asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" MAINTAINSTATE="false" />
          </TD>
      </TR>
      <TR>
          <TD>
               <asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" MAINTAINSTATE="false" />
          </TD>
          <TD>
               <asp:Button RUNAT="server" WIDTH="239" ONCLICK="Button_Submit" TEXT="Upload Image" ID="Button1" NAME="Button1" />
          </TD>
      </TR>
     </TABLE>
     </FORM>
     </BODY>
     </HTML>

UpLoadImage.aspx.cs

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using IC.PhotoController;

namespace TestApp
{
    public class UploadImage : Page
    {
    protected HtmlInputFile UP_FILE;
    protected TextBox txtDescription;
    protected Label txtMessage;
    protected System.Web.UI.WebControls.Button Button1;
    protected Int32 FileLength = 0;

    private void InitializeComponent()
    {
    // do nothing
    }

    protected void Button_Submit(System.Object sender, System.EventArgs e)
    {
        // used to read the properties of image
        HttpPostedFile UpFile = UP_FILE.PostedFile;

        // File size length
        FileLength = UpFile.ContentLength;
        try
        {
            if (FileLength == 0)
            {
                txtMessage.Text = "<b>Please choose a file to upload</b>";
            }
            else
            {
                Byte[] FileByteArray = new Byte[FileLength];
                Stream StreamObject = UpFile.InputStream;
                StreamObject.Read(FileByteArray,0,FileLength);

                // Creates a MemoryStream object from the Byte[]
                MemoryStream mStream =new MemoryStream(FileByteArray);

                // Creates an Image object from the MemoryStream
                // Because PhotoController only returns Image, we have to have one.
                System.Drawing.Image image = System.Drawing.Image.FromStream(mStream);

                // Initializes the PhotoController from the Image object
                IC.PhotoController.Controller objPc = new IC.PhotoController.Controller(image);

                // Resize the image to half size, please refer to Resize method with a float parameter
                image = objPc.Resize(0.5f);

                // Release PhotoController
                objPc.Dispose();

                // We need a new empty MemoryStream
                mStream.Close();
                mStream = new MemoryStream();

                // Save the Image object into MemoryStream. Use Bmp format is a best choice.
                image.Save(mStream, System.Drawing.Imaging.ImageFormat.Bmp);

                // retrieve the Byte[], used to save into DataBase
                FileByteArray = mStream.ToArray();

                // Because mStream.Length returns long, be aware that if the uploaded file size is too large
                FileLength = (Int32) mStream.Length;

                // Release the MemoeryStream resource
                mStream.Close();

                // connect to local SQL Server, no comment for this part
                SqlConnection sqlConn = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");
                String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
                SqlCommand sqlCmd= new SqlCommand(SqlCmd, sqlConn);
                sqlCmd.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
                sqlCmd.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = UpFile.ContentType;
                sqlCmd.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = txtDescription.Text;
                sqlCmd.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
                sqlConn.Open();
                sqlCmd.ExecuteNonQuery();
                sqlConn.Close();
                sqlCmd.Dispose();
                txtMessage.Text = "<p><b>You have uploaded your image successfully!</b>";
            }
        }
        catch (Exception ex)
        {
            txtMessage.Text = ex.Message.ToString();
        }
    }
    }
}

ReadImage.aspx

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

ReadImage.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace TestApp
{
    public class ReadImage : System.Web.UI.Page
    {
        private void Page_Load(object sender, System.EventArgs e)
        {
            int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]);
            SqlConnection sqlConn= new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");
            String strCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
            SqlCommand sqlCmd = new SqlCommand(strCmd, sqlConn);
            sqlCmd.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
            sqlConn.Open();
            SqlDataReader SqlReader = sqlCmd.ExecuteReader();
            SqlReader.Read();
            Response.ContentType = (string)SqlReader["ImageContentType"];
            Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
            Response.End();
            sqlConn.Close();
            sqlCmd.Dispose();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }
    }
}

showimage.htm

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

Exeuction

Compile the project. Run UpLoadImage.aspx to upload an image, and browse showimage.htm to see the uploaded image.

If you have any question about the code above, feel free to write to me.

Send comments about this topic.
Copyright (c) 2006-2007 @ ImageComponent.NET All rights reserved.