Saturday, 11 July 2015

Binary image

You can not simply bind binary image to a control. You have to create an HttpHandler(.ashx) that process the image.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace DisplayImages
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : System.Web.IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
            {
                const string SQL = "SELECT Image,ImageName FROM ImageToDB WHERE [ID] = @ID";
                SqlCommand myCommand = new SqlCommand(SQL, myConnection);
                myCommand.Parameters.AddWithValue("@ID", 4);

                myConnection.Open();
                SqlDataReader myReader = myCommand.ExecuteReader();

                if (myReader.Read())
                {
                    //byte[] buffer = GetPictureFromSomewhere();
                    context.Response.ContentType = "image/jpg";
                    context.Response.OutputStream.Write(((byte[])myReader["Image"]), 0, ((byte[])myReader["Image"]).Length);
                    //(byte[])myReader["Image"]
                    //string base64String = Convert.ToBase64String((byte[])myReader["Image"], 0, ((byte[])myReader["Image"]).Length);
                    //image.ImageUrl = "data:image/jpg;base64," + base64String;
                    //Image1.Visible = true;
                }

                myReader.Close();
                myConnection.Close();
            }           
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}

add the follwong code in default.aspx, design code is below the c# code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DisplayImages
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            // Read the file and convert it to Byte Array
            string filePath = FileUpload1.PostedFile.FileName;
            string filename = Path.GetFileName(filePath);
            string ext = Path.GetExtension(filename);
            string contenttype = String.Empty;

            //Set the contenttype based on File Extension
            switch (ext)
            {
                case ".doc":
                    contenttype = "application/vnd.ms-word";
                    break;
                case ".docx":
                    contenttype = "application/vnd.ms-word";
                    break;
                case ".xls":
                    contenttype = "application/vnd.ms-excel";
                    break;
                case ".xlsx":
                    contenttype = "application/vnd.ms-excel";
                    break;
                case ".jpg":
                    contenttype = "image/jpg";
                    break;
                case ".png":
                    contenttype = "image/png";
                    break;
                case ".gif":
                    contenttype = "image/gif";
                    break;
                case ".pdf":
                    contenttype = "application/pdf";
                    break;
            }
            if (contenttype != String.Empty)
            {

                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs);
                Byte[] bytes = br.ReadBytes((Int32)fs.Length);

                //insert the file into database
                string strQuery = "insert into ImageToDB(Image,ImageName)" +
                   " values (@Image, @ImageName)";
                SqlCommand cmd = new SqlCommand(strQuery);
                cmd.Parameters.Add("@Image", SqlDbType.Binary).Value = bytes;
                cmd.Parameters.Add("@ImageName", SqlDbType.VarChar).Value = filename;
                //cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                InsertUpdateData(cmd);
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "File Uploaded Successfully";
            }
            else
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File format not recognised." +
                  " Upload Image/Word/PDF/Excel formats";
            }
        }

        private Boolean InsertUpdateData(SqlCommand cmd)
        {
            String strConnString = System.Configuration.ConfigurationManager
            .ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConnString);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                return false;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }
        private void BinaryToImage()
        {
            try
            {
                int PictureID = Convert.ToInt32(Request.QueryString["ID"]);

                using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))
                {
                    const string SQL = "SELECT Image,ImageName FROM ImageToDB WHERE [ID] = @ID";
                    SqlCommand myCommand = new SqlCommand(SQL, myConnection);
                    myCommand.Parameters.AddWithValue("@ID", 4);

                    myConnection.Open();
                    SqlDataReader myReader = myCommand.ExecuteReader();

                    if (myReader.Read())
                    {
                        //Response.ContentType = myReader["MIME"].ToString();
                        Response.BinaryWrite((byte[])myReader["Image"]);
                    }

                    myReader.Close();
                    myConnection.Close();
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void Show_Click(object sender, EventArgs e)
        {
            image.ImageUrl = "~/Handler1.ashx";          
            //image.ImageUrl = BinaryToImage();
            //BinaryToImage();
        }
    }
}

Design page of default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayImages.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload"
            OnClick="btnUpload_Click" />
        <br />
        <asp:Button ID="Show" runat="server" OnClick="Show_Click" Text="Show" />
        <br />
        <asp:Label ID="lblMessage" runat="server" Text=""
            Font-Names="Arial"></asp:Label>
        <asp:Image ID="image" runat="server" />
    </form>
</body>
</html>

Web.config file

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />

    <httpModules>
      <add name="Picture" type="Picture"/>
    </httpModules>
  </system.web>
  <connectionStrings>
    <add name="conString" connectionString="Server=SUNDARI-PC\SQLSERVER2012; Database=test; Integrated Security=True"/>
  </connectionStrings >
  <!--<configuration>
  <system.web>
    <httpModules>
      <add name="Picture" type="Picture"/>
     </httpModules>
  </system.web>
</configuration>-->
</configuration>



In your web.config you should add:
<httpHandlers>
    ...
    <add path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
      verb="*" validate="false" />
    ...
</httpHandlers>
To allow Asp.Net to manage every requests containig "ImageHandler.ashx" with the correct IHttpHandler class. And remember to add:
<system.webServer>
    <handlers>
    ...
    <add name="ImageHandler" path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
          verb="*" validate="false" />
    ...
    </handlers>
</system.webServer>