Silverligh 2: How to show images from the database
Rate this content:                         
Dear Reader,

You have to create Converter Class Inteherited from IConverter

 

and the Convert you can set the img src to a http web service url like this

 

public class ImageConverter : IValueConverter

{

    #region IValueConverter Members

   

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   {

          BitmapImage img = new BitmapImage();

        img.UriSource = new Uri("http://localhost:1000/ShowImage.ashx?id=" + value.ToString(), UriKind.Absolute);

           return img;

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

   {

          throw new NotImplementedException();

   }

  

    #endregion

}


Here is the ASHX to load the image from Database

 

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class ShowImage : IHttpHandler

{

    FileStream s;

    public void ProcessRequest(HttpContext context)

    {

        Int32 catId;

        if (context.Request.QueryString["id"] != null)

                catId = Convert.ToInt32(context.Request.QueryString["id"]);

        else

                catId = 1; //throw new ArgumentException("No parameter specified");

 

        if (catId == 0) catId = 1;

        // Convert Byte[] to Bitmap

        Bitmap newBmp = ConvertToBitmap(catId);

       if (newBmp != null)

       {

               newBmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);

               if (s != null)

              {

                   s.Close();

                   s.Dispose();

                   s = null;

              }

             newBmp.Dispose();

       }

}

// Convert byte array to Bitmap (byte[] to Bitmap)

protected Bitmap ConvertToBitmap(int catId)

{

          TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));

          NorthwindDataContext objDC = new NorthwindDataContext();

          var v = objDC.Categories.Single(P => P.CategoryID == catId);

          Bitmap b;

          if (v.Picture != null)

            b = (Bitmap)tc.ConvertFrom(v.Picture.ToArray());

         else

         {

             s = new FileStream(@"E:\Projects\NorthwindMng\NorthwindMng.Web\Nothing.jpg", FileMode.Open);

             b = new Bitmap(s);

          }

          return b;

}

public bool IsReusable

{

       get

      {

          return false;

       }

}

}


   © 2009 Development Next. All Rights Reserved. | Terms of Use | Trademarks