I have used the databae table used in my article.
And then I made the following changes to the sample code of the following article Capture Image (Photo) from Web Camera (webcam) in ASP.Net using C# and VB.Net
Namespaces
using System.IO;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Request.InputStream.Length > 0)
{
using (StreamReader reader = new StreamReader(Request.InputStream))
{
string hexString = Server.UrlEncode(reader.ReadToEnd());
string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
string imagePath = string.Format("~/Captures/{0}.png", imageName);
byte[] bytes = ConvertHexToBytes(hexString);
File.WriteAllBytes(Server.MapPath(imagePath), bytes);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles VALUES(@Name, @ContentType, @Data);SELECT SCOPE_IDENTITY()";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", imageName);
cmd.Parameters.AddWithValue("@ContentType", "image/png");
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
Session["CapturedImageId"] = cmd.ExecuteScalar();
con.Close();
}
}
}
}
}
}
private static byte[] ConvertHexToBytes(string hex)
{
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
[WebMethod(EnableSession = true)]
public static string GetCapturedImage()
{
string url = string.Empty;
int imageId = Convert.ToInt32(HttpContext.Current.Session["CapturedImageId"]);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Data FROM tblFiles WHERE Id = @Id";
cmd.Parameters.AddWithValue("@Id", imageId);
cmd.Connection = con;
con.Open();
byte[] bytes = (byte[])cmd.ExecuteScalar();
url = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
con.Close();
}
}
HttpContext.Current.Session["CapturedImageId"] = null;
return url;
}