Monday, March 27, 2017

Capture an image and upload to database


  • Create a new project.
  • Download WebCam.rar folder through this link and add it to the project.
  • Add an empty folder named "UserImages".
  • Add two web forms as "WebForm1.aspx" and "Image.aspx".

  • Add an image control and a button to WebForm1.aspx like this.
<div style="width: 480px">
<asp:Image ID="ImgPrv" runat="server" Width="480px" Height="360px" />
</div><div style="text-align: center; width: 480px">
<asp:Button ID="btnCapture" runat="server" Text="Capture Image" Height="30px" Width="120px" OnClick="btnCapture_Click" />
</div>
  • WebForm1 code behind
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string imageid = "1";
        if (Session["ImageId"] != null)
        {
            imageid = Session["ImageId"].ToString();
        }
      
        ImgPrv.ImageUrl = "Image.aspx?ImageID=" + imageid + "";
    }
}

protected void btnCapture_Click(object sender, EventArgs e)
{
    string url = "/WebCam/Captureimage.aspx";
    string s = "window.open('" + url + "', 'popup_window', 'width=900,height=460,left=100,top=100,resizable=no');";
    ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
}

  • Change the baseimg.aspx contents of the code behind file as follows.
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        //called page form json for creating imgBase64 in image

        StreamReader reader = new StreamReader(Request.InputStream);
        String Data = Server.UrlDecode(reader.ReadToEnd());
        reader.Close();

        DateTime nm = DateTime.Now;
        string date = nm.ToString("yyyymmddMMss");
        //used date for creating Unique image name
        string filename = date + ".jpg";
        Session["capturedImageURL"] = Server.MapPath("~/Userimages/") + date + ".jpg";

        Session["Imagename"] = date + ".jpg";
        // We can use name of image where ever we required that why we are storing in Session

        drawimg(Data.Replace("imgBase64=data:image/png;base64,", String.Empty), Session["capturedImageURL"].ToString());//To save image within UserImages folder
        // it is method
        // passing base64 string and string filename to Draw Image.

        Session["ImageId"] = imageUpload(filename).ToString();

        System.IO.File.Delete(Server.MapPath("~/Userimages/") + filename);//To delete the image from folder after saving in the database
    }
    catch (Exception ex)
    {
        leave.WriteLog(ex.Message, "WebCam_baseimg- Page_Load");
    }
}

public void drawimg(string base64, string filename)  // Drawing image from Base64 string.
{
    using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(base64);
            bw.Write(data);
            bw.Close();
        }
    }
}

private int imageUpload(string filename)
{
    int imageId = 1;
    try
    {
        StreamReader reader = new StreamReader(Request.InputStream);
        String Data = Server.UrlDecode(reader.ReadToEnd());
        reader.Close();

        string filePath = Server.MapPath("~/Userimages/") + filename;
        string ext = Path.GetExtension(filename);
        ext = ext.ToLower();

        string contenttype = String.Empty;

        switch (ext)
        {
            case ".jpg":
                contenttype = "image/jpg";
                break;
            case ".png":
                contenttype = "image/png";
                break;
            case ".gif":
                contenttype = "image/gif";
                break;
            default:
                break;
        }
        if (contenttype != String.Empty)
        {
            byte[] bytes;

            using (var webClient = new WebClient())
            {
                bytes = webClient.DownloadData(filePath);
            }
            string empId = Session["EmpId"].ToString();
            imageId = imageService.uploadImage(filename, contenttype, bytes, empId);
        }
        return imageId;
    }
    catch (Exception ex)
    {
        leave.WriteLog(ex.Message, "WebCam_baseimg- Page_Load");
        return imageId;
    }
}
  • Add this code inside the Page_Load method of the image.aspx
if (Request.QueryString["ImageID"] != null)
{
    try
    {
        DataTable dt = imageService.retrieveImage(Convert.ToInt32(Request.QueryString["ImageID"]));
        if (dt.Rows.Count > 0)
        {
            byte[] bytes = (byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

retrieveImage method Query

select Name,ContentType,Data from Image where Id='" + imageId + "'

WebForm1.aspx

  • After clicking Capture Image button it opens a popup window.




  • After submitting the captured image, it shows the preview within WebForm1.aspx page.