Silverlight / WPF - how to upload and retrive the image

Asked By sushant kumar kesari
02-Jan-12 06:04 AM
hello frnd

i want to upload  and retrieve the image of emp.
plz reply asap  
  smr replied to sushant kumar kesari
02-Jan-12 06:26 AM
hi

try this

public void Page_Load(object sender, EventArgs e)
{
  SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"));
  SqlCommand myCommand = new SqlCommand("Select * from Person", myConnection);
  
  try {
    myConnection.Open();
    SqlDataReader myDataReader = default(SqlDataReader);
    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
  
    while ((myDataReader.Read())) {
      Response.ContentType = myDataReader.Item("PersonImageType");
      Response.BinaryWrite(myDataReader.Item("PersonImage"));
    }
  
    myConnection.Close();
    Response.Write("Person info successfully retrieved!");
  } catch (SqlException SQLexc) {
    Response.Write("Read Failed : " + SQLexc.ToString());
  }
  
}
  James H replied to sushant kumar kesari
02-Jan-12 06:30 AM
The way we do it is to store the images as blobs in the database (they're fairly small images, 4-500k, so storing them in the db shouldn't cause any perf problems), retreive them as byte arrays, and then use a ValueConverter to convert from byte[] to BitMap. The XAML for the image control looks like this:
 
<Image Source="{Binding Path=RawImageData,
            Converter={StaticResource ByteArrayToBitmapImageConverter},
            Mode=OneWay}" />
The property we bind to in the ViewModel is simply a byte[] like this;
 
private byte[] _rawImageData;
public byte[] RawImageData
{
  get { return _rawImageData; }
  set
  {
    if (value != _rawImageData)
    {
      _rawImageData = value;
      NotifyPropertyChanged("RawImageData");
    }
  }
}
And then the ValueConverte looks like this;
 
  public class ByteArrayToBitmapImageConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    var rawImageData = value as byte[];
    if (rawImageData == null)
      return null;
 
    var bitmapImage = new System.Windows.Media.Imaging.BitmapImage();
    using (var stream = new MemoryStream(rawImageData))
    {
      bitmapImage.BeginInit();
      bitmapImage.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
      bitmapImage.CacheOption = BitmapCacheOption.Default;
      bitmapImage.StreamSource = stream;
      bitmapImage.EndInit();
    }
    return bitmapImage;
    }
 
   public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
   {
     throw new NotImplementedException();
   }
  Vickey F replied to sushant kumar kesari
02-Jan-12 06:36 AM
To save image-


For storing file into database first you have to convert into Byte Array Format, then you can store into DataBase.
Use this sample code for that-


protected void Button1_Click(object sender, EventArgs e)

{

 

 

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];

HttpPostedFile uploadedImage = FileUpload1.PostedFile;

 

uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

 

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

cn.Open();

string strQuery = "insert into EmpTable(empimage) values(@ImageData)";

 

 

SqlCommand cmd = new SqlCommand(strQuery, cn);

cmd.Parameters.Add(new SqlParameter("@ImageData", (object)imageSize));

cmd.ExecuteNonQuery();

 

cmd.ExecuteNonQuery();

cn.Close();
}

USE THIS CODE AND LET ME KNOW.

  Vickey F replied to sushant kumar kesari
02-Jan-12 06:36 AM
To read image-

Use HTTP Handler for this.

use following code-

step1 :

protected void Page_Load(object sender, EventArgs e)

{

ImageButton1.ImageUrl =

 

 

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

}

 

 

 

step2 :

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 and let em know.

  kalpana aparnathi replied to sushant kumar kesari
02-Jan-12 01:47 PM
hi,

Follow The following steps:

Step 1:
Open Visual Studio 2008 > File > New Project > Select the language (C# or VB) > Select ‘Silverlight’ in the Project Types > from the templates, select ‘Silverlight Application’. Type a name ‘AccessImagesInDatabase’ and location for the project and click ok.
Note: If you are unable to view the templates, you do not have Microsoft Silverlight Tools for Visual Studio 2008. Check out this link to see how to obtain it.
Step 2: You will observe that a default page called ‘Page.xaml’ gets created. Remove the <Grid> and replace it with <Canvas> and set its background to Gray. Now add a few controls like the Image, TextBlock, TextBox and Buttons inside the Canvas. After setting a few layout properties, the markup will look similar to the following:
<UserControl x:Class="AccessImagesInDatabase.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Background="Gray">
      <Image x:Name="img1" Width="300" Height="230" Visibility="Visible" HorizontalAlignment="Center"></Image>         
      <TextBlock x:Name="lblEmployee" Text="EmployeeID" Canvas.Top="244" Canvas.Left="10"/>
      <TextBox x:Name="txtEmpID" Canvas.Top="240" Canvas.Left="110" Width="40" Text="1"/>
      <Button x:Name="btnImage" Canvas.Top="270" Canvas.Left="110" Content="Fetch" Click="btnImage_Click"></Button>
    </Canvas>
</UserControl>
 
The ‘btnImage’ is for fetching the image. ‘txtEmpId’ is the textbox where we will enter the EmployeeId whose image is to be retrieved from the database.
Step 3: Since we are retrieving the images from the database, we would need a connection string. Add the following connection string to your web.config
    <connectionStrings>
        <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    </connectionStrings>
Step 4: We will be using an HttpHandler to pull images from the database. Handlers provide a lot of flexibility while accessing server-side resources. To create an Http handler, right click project AccessImagesInDatabase.Web > Add New Item > Generic Handler > DisplayImage.ashx. Add the following code to the handler.
C#
using System;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.Services;
 
 
namespace AccessImagesInDatabase.Web
{
///<summary>
/// Summary description for $codebehindclassname$
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class DisplayImage : IHttpHandler
{
    byte[] empPic = null;
    long seq = 0;
 
    public void ProcessRequest(HttpContext context)
    {
      Int32 empno;
 
      if (context.Request.QueryString["id"] != null)
        empno = Convert.ToInt32(context.Request.QueryString["id"]);
      else
        throw new ArgumentException("No parameter specified");
 
      // Convert Byte[] to Bitmap
      Bitmap newBmp = ConvertToBitmap(ShowEmpImage(empno));
      if (newBmp != null)
      {
        newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        newBmp.Dispose();
      }
    }
 
    // Convert byte array to Bitmap (byte[] to Bitmap)
    protected Bitmap ConvertToBitmap(byte[] bmp)
    {
      if (bmp != null)
      {
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
        Bitmap b = (Bitmap)tc.ConvertFrom(bmp);         
        return b;
      }
      return null;
    }
 
    public byte[] ShowEmpImage(int empno)
    {
      string conn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
      SqlConnection connection = new SqlConnection(conn);
      string sql = "SELECT photo FROM Employees WHERE EmployeeID = @ID";
      SqlCommand cmd = new SqlCommand(sql, connection);
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue("@ID", empno);
      connection.Open();
      SqlDataReader dr = cmd.ExecuteReader();
      if (dr.Read())
      {
        seq = dr.GetBytes(0, 0, null, 0, int.MaxValue) - 1;
        empPic = new byte[seq + 1];
        dr.GetBytes(0, 0, empPic, 0, Convert.ToInt32(seq));
        connection.Close();
      }
 
      return empPic;
    }
 
    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
}
 
}
 
The steps for retrieving images from database, using the handler are as follows:
1.    The EmployeeID whose image is to be retrieved, is passed to the handler via query string. We use the Request.QueryString[“id”] to retrieve the EmployeeID(emp_id) from the handler url. The ID is then passed to the ‘ShowEmpImage()’ method where the image is fetched from the database using SqlDataReader and returned in a byte[] object.
2.    We pass this byte[] to the ConvertToBitmap() function where we use the TypeConverter class to convert a byte array to bitmap.
3.    The last step is to save the image to the page's output stream and indicate the image format as shown here convBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg)
Note: Silverlight does not support .bmp images. For this reason, we set the ImageFormat to Jpeg while saving the image to the OutputStream.
Step 5: The next step is to call this handler from our Silverlight application.
C#
using System.Windows.Media.Imaging;
public partial class Page : UserControl
{
    public Page()
    {
      InitializeComponent();
    }
 
    private void btnImage_Click(object sender, RoutedEventArgs e)
    {
      string imgUri = "http://localhost:57711/DisplayImage.ashx?id=" + Convert.ToInt32(txtEmpID.Text).ToString();
      img1.Source = new BitmapImage(new Uri(imgUri, UriKind.Absolute));     
    }
 
 
}
Fetching Images on Demand using the WebClient class
 
The WebClient class provides functionality for initiating the download request, monitoring the progress of the download, and then finally retrieving the content requested. You can also cancel a download in progress. Let us modify our sample to see how we can use the WebClient class to download images
You need to import the System.Net and System.Windows.Media.Imaging namespaces. Also we will be using event-handlers while using the WebClient, since all requests are asynchronous.
The event-handler we will use is the OpenReadCompleted event handler which occurs when an asynchronous resource-read operation is completed. To request the image as a stream, we will use the OpenReadAsync method of the WebClient. Let us see some code:
First, add a button and a label control to the Page.Xaml. The ‘btnCancel’ is for cancelling the image fetch operation. The ‘txtProgress’ is for displaying status messages at the time of fetching the image and cancelling the operation.
<TextBlock x:Name="txtProgress" Canvas.Top ="240" Canvas.Left="160" Text="" FontSize="10" />
<Button x:Name="btnCancel" Canvas.Top="270" Canvas.Left="150" Content="Cancel" Click="btnCancel_Click"></Button>
 
C#
public partial class Page : UserControl
{
WebClient wc = null;
 
public Page()
{
    InitializeComponent();
}
 
private void btnImage_Click(object sender, RoutedEventArgs e)
{
    string imgUri = "http://localhost:57711/DisplayImage.ashx?id=" + Convert.ToInt32(txtEmpID.Text).ToString();
    txtProgress.Text = String.Empty;
 
    wc = new WebClient();
    wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
    wc.OpenReadAsync(new Uri(imgUri, UriKind.Absolute));
    txtProgress.Text = "Fetching Image...";  
 
    //img1.Source = new BitmapImage(new Uri(s, UriKind.Absolute));    
}
 
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Error == null)
    {
      try
      {
        BitmapImage image = new BitmapImage();
        image.SetSource(e.Result);
        img1.Source = image;
        txtProgress.Text = String.Empty;
      }
      catch(Exception ex)
      {
        txtProgress.Text = "Error while fetching image";
      }
    }
}
 
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
    if (wc.IsBusy)
    {
      wc.CancelAsync();
      txtProgress.Text = "Image fetch cancelled! ";
    }
}
 
}

  Sree K replied to sushant kumar kesari
03-Jan-12 12:36 AM

Quite often, when browsing the web, we encounter a situation where we are required to upload a file. When I want to register myself on a forum, I often get the question if I want to upload an avatar. Or when using a social networking site such as Facebook, I can upload pictures of me doing something that probably no one is interested in. The point I’m trying to make here is that when developing in Silverlight, we’ll also come in a situation where we want our users to upload files such as images to the server. Next to uploading, users may want to download files such as images, which are stored as a physical file on the server as well.

In both cases, WCF can help us out, allowing us to create services that are capable of working with an uploaded file as well as processing a requested file for download. In this article, I’ll be showing a sample Silverlight application where users can upload and download images from using a WCF service. The interface is very simple; a screenshot is shown below.

Picture1

Included with this article is the sample code, which can be downloaded here. We’ll be using this code to show how the upload and download process works.


http://www.silverlightshow.net/items/Uploading-and-downloading-images-from-WCF-in-Silverlight.aspx

Create New Account
help
Is Visual Studio self-hosting ? .NET Framework Does Microsoft use Visual Studio IDE, Visual Studio Debugger, Visual Studio Linker and Visual Studio compiler for developing Visual Studio ? Or is Visual Studio not good enough for them and are they in fact using something else ? Visual Studio Development Discussions Visual Studio (1) Linker (1) Don't spread it around but they
Visual Studio vs Visual Web Developer .NET Framework Hi! The Visual Web Developer is better than Visual Studio 2005 for web development? All the Ajax examples are developed in Visual Web Developer. Thanks ASP.NET Discussions Visual Studio 2005 (1) Visual Studio (1) Office (1) Compiler (1) Library (1) Control (1) Coverage (1) Database (1) I think you're confusing the products here. Visual Web Developer IS the web design portion of Visual Studio. Visual Studio includes a number
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 Visual designer. Visual Studio 2010 provides a new project template for Visual Web Part. This project provides us
1. RFD: comp.lang.visual moderated (remove) C++ / VB REQUEST FOR DISCUSSION (RFD) moderated group comp.lang.visual This is a formal Request for Discussion (RFD) to remove moderated newsgroup comp.lang.visual. NEWSGROUPS LINE: comp.lang.visual General discussion of visual programming languages. (Moderated) DISTRIBUTION: news.announce.newgroups news.groups.proposals comp.lang visual PROPONENT: Alexander Bartolich <alexander.bartolich@gmx.at> CHARTER OF COMP.LANG.VISUAL A forum for general discussion of visual programming languages. A working definition of visual programming languages is posted in the regular comp