ADO/ADO.NET - show image in image control  ADO/ADO.NET - show image in image control

Asked By Nitish Gupta
08-Aug-11 11:52 PM
hello,
i am working in project in which there is registration form.
i this form i want to upload image of candidate and show image  in image control in form..
i have store image path in database and want to show image in image control through this image path..when page loads..
i am using asp.net C# with visual studio 2008 and sql server 2005.
thanx in advance..
  Riley K replied to Nitish Gupta
08-Aug-11 11:57 PM
hi,

use this below uploading images in File System and storing image paths in the DataBase.

Get the file name and use Server.Mappath to save to a folder and save the path to database


protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
 
//Save images into Images folder
 
fileuploadimages.SaveAs(Server.MapPath("Images/"+filename));
 
//Getting dbconnection from web.config connectionstring
 
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
//Open the database connection
con.Open();
 
//Query to insert images path and name into database
 
SqlCommand cmd = new SqlCommand("Insert into ImagesPath(ImageName,ImagePath) values(@ImageName,@ImagePath)", con);
 
//Passing parameters to query
 
cmd.Parameters.AddWithValue("@ImageName", filename);
cmd.Parameters.AddWithValue("@ImagePath", "Images/" + filename);
cmd.ExecuteNonQuery();
 
//Close dbconnection
 
con.Close();
 
Response.Redirect("~/Default.aspx");
}

Try and let me know
  Vickey F replied to Nitish Gupta
09-Aug-11 12:00 AM

First you have to store image in your local project folder.
second read path from database and assign to ImageUrl Property of Image Control.


try this code-


protected void GetDetails_Click(object sender, EventArgs e)
{

{

SqlConnection con = new SqlConnection("con string ");
SqlDataAdapter da;
string mySQL = "SELECT imgPath FROM emptable where empid='" + TxtEmpId.Text + "' ";
da = new SqlDataAdapter(mySQL, con);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);

if(ds.Tables[0].Rows.Count>0)
{

//Now Filling Details-

Image1.ImageURL=ds.Tables[0].Row[0]["imgPath"].ToString();
}
}

Try this code and let me know.

  James H replied to Nitish Gupta
09-Aug-11 12:16 AM
  • http://www.codeproject.com/KB/web-image/ThumbViewerControl/ThumbViewerControl_src.zip

Screenshot - ThumbViewerControl1.jpg

Introduction

Generating thumbnail images and building a user interface for viewing the full size images can be time consuming. Using an HttpHandler to generate thumbnail images at runtime is a well-documented topic in numerous articles. The ThumbViewer control uses this technique, but its main feature is that it has a UI for downloading and viewing fullsize images built into the control.

Background

I originally developed the UI functionality of the ThumbViewer control for viewing photos on my personnal website using JavaScript and HTML. By using embedded resources and adding an HttpHandler, it was quite easy to wrap this up as an ASP.NET control.

Design Objectives

The design objectives of the control:

  • Display a thumbnail image on a web page with a means of requesting the full image.
  • When the user requests the full size image, stream it to the browser and display it.
  • While viewing the full image, the original web page is not closed or does not need to be reloaded when the full image is closed.
  • Display the full image without using a separate browser window.
  • Allow the user to choose which full size images to view without having to view all images in a slideshow type UI.
  • Maximize the size of the full image for the browser window size.

Using the ThumbViewer Control

In the Toolbox in Visual Studio 2005 right-click and select "Choose Items...". On the Choose Toolbox Items dialog click on Browse and select the Bright.Controls.dll assembly. This will add the ThumbViewer control to the toolbox.

Screenshot - ThumbViewerControl2.jpg

To register the ThumbViewer HttpHandler with your application, add the following to the <system.web> section of your web.config. (This step is not necessary if you plan to use your own thumbnail images)

<!-- Register the ThumbViewer HttpHandler -->
    <httpHandlers>
      <add verb="GET" path="ThumbHandler.ashx" 
          type="Bright.WebControls.ThumbHandler"/>
    </httpHandlers>

Drag the ThumbViewer control onto a page like any other web control and set its properties.

Screenshot - ThumbViewerControl3.jpg

Properties

  • ImageUrl - The URL of the full size image
  • ThumbUrl - The URL of the thumbnail image
  • Title - The Title of the image, this is displayed when viewing the fullsize image
  • ModalDisplayMode - The mode of the modal display, Stretch, Fixed or Disabled
  • ModalImagePadding - The padding of the modal display if ModalDisplayMode is set to Stretch
  • ModalFixedWidth - The width of the modal display if ModalDisplayMode is set to Fixed
  • ModalFixedHeight - The height of the modal display if ModalDisplayMode is set to Fixed

There are several ways to use the ThumbViewer Control to display images.

Here are the options depending on the types of images you want to display

You already have thumbnail images:

  • Set the ImageUrl to the full size image location and set the ThumbUrl to the thumbnail image location.

You don't have thumbnail images:

  • Set the ImageUrl to the full size image location and leave the ThumbUrl property empty, the thumbnail image will be generated at runtime.

You have small images which and you want to display a larger version of the same image:

  • Set the ThumbUrl to the full size image location and leave the ImageUrl property empty.

Here are the ModalDisplayModes for the full size image

Stretch
Stretch is the default display mode and will utilise the full size of the browser window while keeping the same aspect ratio as the thumbnail image.

Fixed
The Fixed display mode will display the image to the size specified in the ModalFixedWidth and ModalFixedHeight properties.

Disabled
The Disabled display mode will not allow the full size image to be viewed.

How it Works

C# Code

The Bright.WebControls assembly contains two classes, ThumbViewer.cs and ThumbHandler.cs. The ThumbViewer.cs class is derived from the System.Web.UI.WebControls.Image control.

Some of the Image properties are overidden:

    public override string ImageUrl {}
    public override Unit Width {}
    public override Unit Height {}

and some custom properties and an enum are added:

    public virtual string ThumbUrl {}
    public virtual string Title {}
    public virtual Unit ModalImagePadding {}
    public virtual Unit ModalFixedWidth {}
    public virtual Unit ModalFixedHeight {}
    public ModalDisplayModeOptions ModalDisplayMode {}

    // ModalDisplayModeOptions enum

    public enum ModalDisplayModeOptions
    {
        Stretch,
        Fixed,
        Disabled
    }

The OnInit and some of the Render methods are overidden to setup various aspects of the contol.

    protected override void OnInit(EventArgs e)
    {
        // Register Javascript and CSS files as the control is initialised

        SetupIncludes();

        base.OnInit(e);
    }
    protected override void Render(HtmlTextWriter writer)
    {
        // Setup up the ImageUrl & ThumbUrl

        SetupUrls();

        base.Render(writer);
    }
    public override void RenderBeginTag(HtmlTextWriter writer)
    {
        if (!DesignMode)
        {
            // Before the first control, write out the Modal Divs

            SetupModal(writer);
        }
        base.RenderBeginTag(writer);
    }
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        if (!DesignMode)
        {
            // Setup the image Attributes

            SetupAttributes(writer);
        }

        base.AddAttributesToRender(writer);     
    }
  • OnInit calls SetupIncludes(); which registers the JavaScript and stylesheet resources with the page.
  • Render calls SetupUrls(); which modifies the src of the image as required.
  • RenderBeginTag calls SetupModal(writer); which adds the HTML for the modal. The modal is only added for the first control on the page and shared by all the others.
  • AddAttributesToRender calls SetupAttributes(writer); which adds the Onclick event handler to the images.

The private methods are well commented in the source code download so I won't go into detail here.

The ThumbHandler.cs class implements the IHttpHandler interface.

    public class ThumbHandler : IHttpHandler {}

The thumbnail image creation is handled in the ProcessRequest method.

public void ProcessRequest(HttpContext context)
{
    // Get the QueryString parameters passed

    string _imagePath = context.Request.QueryString["i"] == null ?
        string.Empty : context.Request.QueryString["i"].ToString();
    int _thumbWidth = context.Request.QueryString["w"] == null ?
        100 : int.Parse(context.Request.QueryString["w"].ToString());
    int _thumbHeight = context.Request.QueryString["h"] == null ?
        100 : int.Parse(context.Request.QueryString["h"].ToString());

    // Create a thumb image from the source image

    System.Drawing.Image _sourceImage = System.Drawing.Image.FromFile(
        context.Server.MapPath(_imagePath));
    System.Drawing.Image _thumbImage = this.CreateThumbnail(
        _sourceImage, _thumbWidth, _thumbHeight);

    // Save the thumb image to the OutputStream

    _thumbImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
    
private System.Drawing.Image CreateThumbnail(System.Drawing.Image image, 
    int thumbWidth, int thumbHeight)
{
    return image.GetThumbnailImage(
        thumbWidth,
        thumbHeight, 
        delegate() { return false; }, 
        IntPtr.Zero
        );
}

The querystring parameters are retrieved and then the image is passed to CreateThumbnail to generate the thumbnail with the dimensions passed. The thumbnail image is then saved to the OutputStream.

Embedded Resources

The embedded resources are contained in the Resources folder:

  • ThumbViewer.js - Handles the modal display of the full size image.
  • ThumbViewer.css - Contains the styles for the modal display.
  • Progress.gif - Animated image which is displayed while the full size image is loading.

These resources are registered in the AssemblyInfo.cs class.

    [assembly: WebResource("Bright.WebControls.Resources.ThumbViewer.css", 
        "text/css")]
    [assembly: WebResource("Bright.WebControls.Resources.ThumbViewer.js", 
        "text/javascript", PerformSubstitution = true)]
    [assembly: WebResource("Bright.WebControls.Resources.Progress.gif", 
        "image/gif")]
  Ravi S replied to Nitish Gupta
09-Aug-11 12:17 AM
HI

Try this simple by giving the path:

Image1.ImageUrl = "status/available.jpg";
  Ravi S replied to Nitish Gupta
09-Aug-11 12:17 AM
HI

you can try this also

When you are saving or uploading file to your directory on server, it needs Rooted path,but while getting the saved image back we can directly refer that directory and get the uploaded image just after uploading, see the small code snippet

protected void btn_Click(object sender, EventArgs e)
{
   
   if (flUpload.HasFile)
   {
   flUpload.SaveAs(Server.MapPath("Images") + "//" + flUpload.FileName);
   imgUpload.ImageUrl ="Images/" + flUpload.FileName;
   }
}

Here you can see i have just taken back the uploaded image in image control called imgUpload and over there i have not done server.mappath but instead, i have directly refer images directory where image has been uploaded, see the following snapshot of before uploading and after uploading
  Anoop S replied to Nitish Gupta
09-Aug-11 12:52 AM

u simply use image control in .aspx page as follows

<asp:Image ID="Image1" runat="server" Height="200" Width="200"  />

and in code file

u set the ImageUrl propery in after check yr condition like

//select image path depends upon your user specific condition

strImgPath =  server.mappath(filename);

//and then set this path name to image control at run time

ImageUrl=strImgPath ;

  dipa ahuja replied to Nitish Gupta
09-Aug-11 03:42 AM
hi.....

when you create new user page, there may be one Image control.. in that set imageurl as ur default image, such as default.jpg..

now when user want to choose any other image , he will select any image by using image upload button..

but at the time of creating account if user dont want to upload image then this default.jpg will be selected as his/her display pictr.

so in that case when u fire  insert query , there may be a field like "imageurl" in that field if user selected any image then insert that uploaded image, If not then insert default.jpg as user's  imageurl field of table..

try this code:
protected void btnUpload_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFile)
  {
  try
  {
    string FolderPathToSave = Server.MapPath("~/images");
 
    //Save Image in Images Folder
 
    FileUpload1.SaveAs(FolderPathToSave + @"\" + FileUpload1.FileName);
    Status.Text = "File name: " +
      FileUpload1.PostedFile.FileName + "<br>";
    //Save ImageURL in Database
 
    string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
    SqlConnection connection = new SqlConnection(conn);
    connection.Open();
    SqlCommand comm = new SqlCommand("Insert into table (name,url) values (@name,@url)", connection);
    comm.Parameters.AddWithValue("name""file1");
    comm.Parameters.AddWithValue("url"Path.GetFileName(FileUpload1.PostedFile.FileName));
    comm.ExecuteNonQuery();
    connection.Close();
 
  }
  catch (Exception ex)
  {
    Status.Text = "ERROR: " + ex.Message.ToString();
    
  }
  Image1.ImageUrl = "images/" + FileUpload1.FileName;
  }
}
Create New Account
help
NET 2003 Professional I had VS .NET 2003 Professional installed on my machine and also Visual Web Developer 2005 Express Edition. Both work and after a few days both stopped working. I uninstalled Web This step-by-step article describes two methods that you can use to remove Microsoft Visual Studio .NET 2003 from your computer. Back to the top Back to the top Remove Visual Studio .NET 2003 by using the Add or Remove Programs tool loadTOCNode(2, 'summary'); To remove Visual Studio .NET 2003 by using the Add or Remove Programs tool in Control Panel, follow these
visual studio installation problem Actually, my OS is Windows Xp with service pack2.I added service pack3 to install visual studio2010.after that i tryed to installed, but am getting SETUP FAILED due to "Windows XP is not installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed. [08 / 10 / 11, 14:26:01
SharePoint 2010 Visual Web Parts using Visual Studio 2010, Feature Designer and Package Designer How to create a Visual Web Part in Visual Studio 2010 and how to deploy it to the SharePoint 2010 team site. What is a Visual Web Part? With SharePoint 2007 and Windows SharePoint Services 2007 or previous versions, to develop mistake while writing the design code could mess up the whole layout. But now using Visual Studio 2010, we can develop a custom web part for SharePoint 2010 site using the
help. I would greatly appreciate it. Thanks, George - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - see below for IIS6.log - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - [3 / 5 / 2005 12:57:45] LogFile Open. [* ** ** Search on FAIL / MessageBox keywords for failures * ** **]. [3 / 5 / 2005 12:57:45] Initial thread locale = 409 [3 / 5 / 2005 12:57:45] returned from France fix with locale 409 [3 / 5 2005 12:57:45] OC_PREINITIALIZE:[iis] End. Return = 1 (OCFLAG_UNICODE) [3 / 5 / 2005 12:57:45] OC_INIT_COMPONENT:[iis, (null)] Start. [3 / 5 / 2005 12:57:45] OC_INIT_COMPONENT:3 / 31 / 2003 12:00:00 A_ __ __ __ 6.0.2600.2180 0.2600.2180 (xpsp_sp2_rtm.040803-2158): x86: C: \ WINDOWS \ system32 \ Setup \ iis.dll [3 / 5 / 2005 12:57:45] OC_INIT_COMPONENT:Set UnAttendFlag:OFF (File = '') [3 / 5 / 2005 12:57:45] OC_INIT_COMPONENT:CmdLine = "C: \ WINDOWS \ system32 \ sysocmgr.exe" / y / i:C: \ WINDOWS \ system32