title: Displaying image retrieved from database to image control
body: <p>I need help in displaying an image from database. I've read that it's efficient to use handlers to load image from database to a handler. But I don't want to use handlers because I assumed that when you set the imageUrl to a handler, the image will only be loaded upon pageLoad. In my case, I have a existing image present at my img tag, then after uploading, I need to change that image. I used ajaxFileUploader plugin and successfully uploaded and save the image to the database. My problem now is retrieving it.</p>
  
  <p></p>
  
  <p>upon successful jquery ajax call, I will be calling a webmethod using ajax. Here is my code for that:</p>
  
  <pre><code>$.ajaxFileUpload
  (
      {
          url: 'AjaxFileUploader.ashx',
          secureuri: false,
          fileElementId: 'uploadControl',
          dataType: 'json',
          data: '{}',
          success: function () {
              $.ajax({
  
                  type: "POST",
  
                  url: "UserProfile.aspx/displayImage",
  
                  data: jsonData,
  
                  contentType: "application/json; charset=utf-8",
  
                  dataType: "json",
  
                  success: function (mydata) {
                  }
              });
          },
          error: function () {
  
          }
      }
  )
  </code></pre>
  
  <p>In my ImageRetrieval, the following codes are present:</p>
  
  <pre><code>    public void ProcessRequest(HttpContext context)
      {
      string userid = context.Request.QueryString["user"];
          DBAccess dbacc = new DBAccess();
          DataTable dt = dbacc.getImage(userid);
          byte[] image = ((byte[])dt.Rows[0]["UserImage"]);
          System.Drawing.Image img = byteArrayToImage(image);
  
          MemoryStream stream = new MemoryStream();
          img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
          img.Dispose();
          stream.Position = 0;
          byte[] data = new byte[stream.Length];
          stream.Read(data, 0, (int)stream.Length);
          stream.Dispose();
          context.Response.Clear();
          context.Response.ContentType = "image/jpeg";
          context.Response.BinaryWrite(data);
  }
  </code></pre>
  
  <p>My Byte to Image conversion:</p>
  
  <pre><code>    public Image byteArrayToImage(byte[] byteArrayIn)
      {
          MemoryStream ms = new MemoryStream(byteArrayIn);
          Image returnImage = Image.FromStream(ms);
          return returnImage;
      }
  </code></pre>
  
  <p>My database access:</p>
  
  <pre><code>    public DataTable getImage(string userid)
      {
          DataTable dtGetImage = new DataTable();
  
          using (SqlConnection cn = MySqlDataAccess.sqlDataAccess.MySqlConnection())
          {
              using (SqlCommand cmd = MySqlDataAccess.sqlDataAccess.MySqlCommand(cn, CommandType.Text, "SELECT * FROM Images WHERE UserId = @userid"))
              {
                  cmd.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid;
  
                  using (SqlDataAdapter da = MySqlDataAccess.sqlDataAccess.MySqlAdapter(cmd))
                  {
                      da.Fill(dtGetImage);
                  }
              }
          }
  
          return dtGetImage;
      }
  </code></pre>
  
  <p>FileUploader.ashx code:</p>
  
  <pre><code>    public void ProcessRequest(HttpContext context)
      {
         string path = context.Server.MapPath("~/Temp");
              if (!Directory.Exists(path))
                  Directory.CreateDirectory(path);
  
              var file = context.Request.Files[0];
  
              string userid = context.Request.QueryString["user"];
  
              string fileName;
  
              if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
              {
                  string[] files = file.FileName.Split(new char[] { '\\' });
                  fileName = files[files.Length - 1];
              }
              else
              {
                  fileName = file.FileName;
              }
              string fileType = file.ContentType;
              string strFileName = fileName;
  
              int filelength = file.ContentLength;
              byte[] imagebytes = new byte[filelength];
              file.InputStream.Read(imagebytes, 0, filelength);
              DBAccess dbacc = new DBAccess();
              dbacc.saveImage(imagebytes, userid);
  
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
              var result = new { name = file.FileName };
              context.Response.Write(serializer.Serialize(result));
      }
  </code></pre>
  
  <p>Help please! Thanks!</p>