ASP.NET - image display - Asked By msakt on 28-May-12 01:51 AM

{
   fupBill.SaveAs(Server.MapPath(@"Upload\UploadBill\" + fupBill.FileName));
      string imageFlePath = Server.MapPath(@"Upload\UploadBill\" + fupBill.FileName);
      Image1.ImageUrl = imageFlePath;
      Image1.DataBind();
}

image display without use folder.....for example  browse image and and click upload button show particular image display on image control...here dont use folder for save images
Neha Garg replied to msakt on 28-May-12 02:02 AM
HI...msakt,

For displaying the uploaded image without saving it into database folder you have to use the below code:


HttpPostedFile file = context.Request.Files[0];
          byte[] buffer = new byte[file.ContentLength];
          file.InputStream.Read(buffer, 0, file.ContentLength);
  
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
Jitendra Faye replied to msakt on 28-May-12 02:03 AM
For this you have to show that image into database and then you have to access that image from database to show in image control.

for this use HttpHandler like this-

For Retrieving image from database and displaying, you can use Handler.

use following code-

step1 :


protected void Page_Load(object sender, EventArgs e)

{

Image1.ImageUrl = "handler1.ashx?EmpID='1'";

}


step2:   handler code


public void ProcessRequest(HttpContext context)

{

SqlConnection cn = new SqlConnection("YOUR CONNECTION STRING");

cn.Open();

string empid = context.Request.QueryString["EmpID"].ToString();

SqlCommand cmd = new SqlCommand("select empimage from empimageTABLE where empid=" + empid, cn);

SqlDataReader dr = cmd.ExecuteReader();

dr.Read();

context.Response.BinaryWrite((byte[])dr["empimage"]);

dr.Close();

cn.Close();

}

try this code and let me know.




Neha Garg replied to msakt on 28-May-12 02:06 AM
Hi ....

See the below code:

public class GenericHandler : IHttpHandler, IRequiresSessionState
{
  public void ProcessRequest(HttpContext context)
  {
    string f = context.Request.QueryString.Get("f");
    string s = context.Request.QueryString.Get("s");
    if (!string.IsNullOrEmpty(f))
    {
      HttpPostedFile file = context.Request.Files[f];
      if (file == null)
        HttpContext.Current.ApplicationInstance.CompleteRequest();
      else
      {
        List<string> keys = new List<string>();
        foreach (string key in context.Session.Keys) if (key.StartsWith(f)) keys.Add(key);
        foreach (string key in keys) context.Session.Remove(key);
        System.Drawing.Image image = Bitmap.FromStream(file.InputStream);
        context.Session[f + "image"] = image;
        context.Session[f + "contextType"] = context.Request.Files[0].ContentType;
        context.Response.Flush();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
      }
    }
    else if (!string.IsNullOrEmpty(s))
    {
      string ck = s + "contextType";
      string ik = s + "image";
      if (context.Session[ck] == null || context.Session[ik] == null)
      {
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        if (context.Session[ck] != null) context.Session.Remove(ck);
        if (context.Session[ik] != null) context.Session.Remove(ik);
      }
      else
      {
        using (System.Drawing.Image image = (System.Drawing.Image)context.Session[ik])
        {
          context.Response.Clear();
          context.Response.ClearHeaders();
          string type = context.Session[ck].ToString().ToLower();
          System.Drawing.Imaging.ImageFormat format =
                              System.Drawing.Imaging.ImageFormat.Gif;
          bool isValid = true;
          if (type.Contains("bmp")) format = System.Drawing.Imaging.ImageFormat.Bmp;
          else if (type.Contains("jpg") || type.Contains("jpeg")) format =
                              System.Drawing.Imaging.ImageFormat.Jpeg;
          else if (type.Contains("png")) format = System.Drawing.Imaging.ImageFormat.Png;
          else isValid = false;
          if (isValid)
          {
            using (MemoryStream stream = new MemoryStream())
            {
              image.Save(stream, format);
              context.Response.BinaryWrite(stream.ToArray());
              context.Response.ContentType = type;
            }
          }
          context.Session.Remove(ck);
          context.Session.Remove(ik);
          HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
      }
    }
  }
  public bool IsReusable
  {
    get
    {
      return false;
    }
  }
}
Somesh Yadav replied to msakt on 28-May-12 02:06 AM
check this,
http://www.dotnetspider.com/resources/22367-using-javascript-display-image-image-control.aspx
Chintan Vaghela replied to msakt on 28-May-12 02:20 AM

Hello,

This Code using LINQ

Pass ImageHandler to Image Control as following way

 

  int passID = 1; /// Pass DB Table inserted Image Primary ID

        img.ImageUrl = "ImageHandler.ashx?ImID=" + passID;

Create one Image Hadler to Display Byte[] Image from Database

 

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;

using System.Web;

using System.Linq;

 

public class ImageHandler : IHttpHandler

{

 

    public void ProcessRequest(HttpContext context)

    {

   

      DataClassesDataContext dc = new DataClassesDataContext();

      int imageid = Convert.ToInt32(context.Request.QueryString["ImID"]);

      var lst = (from empDetail in dc.cust_portfolio_images

           where empDetail.portfolio_id == imageid

           select

             new

             {

               ImageData = empDetail.portfolio_snaps

 

             }).SingleOrDefault();

      if (lst != null)

      {

        context.Response.BinaryWrite(lst.ImageData.ToArray());

        context.Response.End();

      }

    }

 

    public bool IsReusable

    {

      get

      {

        return false;

      }

    }

 

}

Hope this helpful!

Thanks

 

 

 

dipa ahuja replied to msakt on 28-May-12 06:44 AM
try this code. This will save your file in the images folder and if the image file already exist then it wil rename it.
 
<asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
<asp:Button ID="UploadButton" Text="Upload file" OnClick="UploadButton_Click" runat="server"/>
 
 
protected void UploadButton1_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFile)
  {
    // Call a helper method routine to save the file.
    // Specify the path to save the uploaded file to.
    string savePath = Server.MapPath("images/");
 
    // Get the name of the file to upload.
    string fileName = FileUpload1.FileName;
 
    // Create the path and file name to check for duplicates.
    string pathToCheck = savePath + fileName;
 
    // Create a temporary file name to use for checking duplicates.
    string tempfileName = "";
 
    // Check to see if a file already exists with the, same name as the file to upload.      
    if (File.Exists(pathToCheck))
    {
      int counter = 2;
      while (File.Exists(pathToCheck))
      {
        // if a file with this name already exists,
        // prefix the filename with a number.
        tempfileName = counter.ToString() + fileName;
        pathToCheck = savePath + tempfileName;
        counter++;
      }
 
      fileName = tempfileName;
 
      // Notify the user that the file name was changed.
      UploadStatusLabel.Text = "A file with the same name already exists." +
        "<br />Your file was saved as " + fileName;
    }
    else
    {
      // Notify the user that the file was saved successfully.
      UploadStatusLabel.Text = "Your file was uploaded successfully.";
    }
 
    // Append the name of the file to upload to the path.
    savePath += fileName;
    FileUpload1.SaveAs(savePath);
     
    Image1.ImageUrl = "images/" + FileUpload1.FileName;
  }
  else
  {
    // Notify the user that a file was not uploaded.
    UploadStatusLabel.Text = "You did not specify a file to upload.";
  }
}