Inserting and Retrieving Image using LINQ to SQL from ASP.Net Application

Objective

In this article, I am going to show you

1. How to insert an image from ASP.Net application to SQL Server using LINQ to SQL.

2. How to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.

Block Diagram of solution

clip_image002

Description of table

For my purpose, I have created a table called ImageTable.

clip_image003

1. Id is primary key.

2. Name column will contain name of the image file.

3. FileSource column will contain binary of image. Type of this column is image.

Create ASP.Net Web Application

Open visual studio and from File menu select New Project and then from Web tab select new web application. Give meaningful name to your web application.

Create DBML file using LINQ to SQL class.

For detail description on how to use LINQ to SQL class read HERE

1. Right click on the project and select add new item.

2. From DATA tab select LINQ to SQL Class.

3. On design surface select server explorer.

4. In server explorer and add new connection.

5. Give database server name and select database.

6. Dragged the table on the design surface.

Once all the steps done, you will have a dbml file created.

Design the page

1. I have dragged one FileUpload control and a button for upload purpose.

2. One text box. In this text box user will enter Id of the image to be fetched.

3. One button to fetch the image from database.

4. One Image control to display image from database.

Default.aspx

clip_image005

Saving image in table

On click event of Button 1 Image upload will be done.

clip_image007

In this code

1. First checking whether FileUplad control contains file or not.

2. Saving the file name in a string variable.

3. Reading file content in Byte array.

4. Then converting Byte array in Binary Object.

5. Creating instance of data context class.

6. Creating instance of ImageTable class using object initializer. Passing Id as hard coded value. Name as file name and FileSource as binary object.

Retrieving Image from table

On click event of button2 Image will be fetched of a particular Id. Image Id will be given by user in text box.

clip_image009

In above code, I am calling a generic HTTP handler. As query string value from textbox1 is appended to the URL of HTTP handler. To add HTTP handler, right click on project and add new item. Then select generic handler from web tab.

clip_image011

In above code,

1. Reading query string in a variable.

2. Calling a function returning ShowEmpImage returning Stream.

3. In ShowEmpImage , creating object DataContext class .

4. Using LINQ fetching a particular raw from table of a particular ID.

5. Converting image column in memory stream. In this case FileSource column is containing image.

6. Converting stream into byte array.

7. Reading byte array in series of integer.

8. Using Output stream writing the integer sequence.

Running application

 

output1 Output2

 Output3

For your reference entire source code is given below ,

Default.aspx.cs

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.Web.UI;

    6 using System.Web.UI.WebControls;

    7 using System.Data.Linq;

    8 using System.IO;

    9 

   10 namespace uploadingImageusingLInqtoSQl

   11 {

   12     public partial class _Default : System.Web.UI.Page

   13     {

   14         protected void Page_Load(object sender, EventArgs e)

   15         {

   16 

   17         }

   18 

   19         protected void Button1_Click(object sender, EventArgs e)

   20         {

   21             if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)

   22             {

   23                 string fileName = FileUpload1.FileName;           

   24 

   25                 byte[] fileByte = FileUpload1.FileBytes;

   26                 Binary binaryObj = new Binary(fileByte);

   27                 DataClasses1DataContext context = new DataClasses1DataContext();

   28                 context.ImageTables.InsertOnSubmit(

   29                     new ImageTable { Id = “xyz”,

   30                         Name = fileName,

   31                         FileSource = binaryObj });

   32                 context.SubmitChanges();

   33 

   34 

   35             }

   36         }

   37 

   38         protected void Button2_Click(object sender, EventArgs e)

   39         {

   40 

   41 

   42             Image1.ImageUrl = “~/MyPhoto.ashx?Id=”+TextBox1.Text;

   43 

   44         }

   45 

   46 

   47     }

   48 }

   49 

 

MyPhoto.ashx.cs

 

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Web;

    5 using System.IO;

    6 using System.Web.UI;

    7 using System.Web.UI.WebControls;

    8 

    9 

   10 namespace uploadingImageusingLInqtoSQl

   11 {

   12     /// <summary>

   13     /// Summary description for MyPhoto

   14     /// </summary>

   15     public class MyPhoto : IHttpHandler

   16     {

   17 

   18         public void ProcessRequest(HttpContext context)

   19         {

   20 

   21             string id = context.Request.QueryString[“Id”];

   22             context.Response.ContentType = “image/jpeg”;

   23             Stream strm = ShowEmpImage(id);

   24             byte[] buffer = new byte[4096];

   25             int byteSeq = strm.Read(buffer, 0, 4096);

   26             while (byteSeq > 0)

   27             {

   28                 context.Response.OutputStream.Write(buffer, 0, byteSeq);

   29                 byteSeq = strm.Read(buffer, 0, 4096);

   30             }  

   31         }

   32 

   33         public Stream ShowEmpImage(string id)

   34         {

   35             DataClasses1DataContext context1 = new DataClasses1DataContext();

   36             var r = (from a in context1.ImageTables where a.Id == id select a).First();

   37             return new MemoryStream(r.FileSource.ToArray());         

   38 

   39         }

   40         public bool IsReusable

   41         {

   42             get

   43             {

   44                 return false;

   45             }

   46         }

   47     }

   48 }

 

Thanks for reading. I hope this post is useful. Happy Coding.

31 responses to “Inserting and Retrieving Image using LINQ to SQL from ASP.Net Application”

  1. Satish Kamuju

    Hello Dhananjay Kumar,
    Thanq Dude Working Fine And Good
    Thanq So Much

  2. Navaneethakrishnan

    It is really usefull to the beginners

  3. Thank you, this helpful for me :).

  4. pls send me code in .net 2010 using silverlight that how to store the images in folder.

  5. very nice BOSS……..
    Good Luck……..

  6. nice sir..thax a lot…..i m facing prob to retrive image..hope this can do my work easy

  7. Hello!

    Thank you very much for this code.
    Unfortunately, I always get the following error:

    String or binary data would be truncated.\r\nThe statement has been terminated.

    I tried smaller images and the problem remains.

    Please advise!
    My e-mailaddress: jangroven@gmail.com

  8. (The problem occurs at:
    context.SubmitChanges(); (line 32 on Default.aspx.cs)

  9. THANKS A LOT.;……..SIL

  10. This code is good,can you please explain how we can alter the image?

  11. Great Example !!! Thanks a Lot 🙂

  12. I did the same example and it works fine, no error cach, nothing. But I never get the Image on the Image control. Any idea?, please I will be very grateful. Thanks

  13. K. Venketesh babu

    How 2 get the keyword(Binary) in our .cs page. actually i m tring but not getting. can u say any other method 2 get that keyword ya any namespace we have 2 include 2 get access 2 the binary keyword .cs page. well i m using VS 2008.

  14. How 2 get the keyword(Binary) in our .cs page. actually i m tring but not getting. can u say any other method 2 get that keyword ya any namespace we have 2 include 2 get access 2 the binary keyword .cs page. well i m using VS 2008.

  15. thanks alot..

  16. i want to resize image size ??????

  17. thankyou this is helpfl for me………..

  18. Nice Article.

  19. thanks dhananjay
    very good post

  20. Dhananjay Kumar

    Glad it is useful.
    Thanks
    DJ

  21. Everyone loves what you guys are up too. This sort of clever work and exposure!

    Keep up the great works guys I’ve added you guys to my own blogroll.

  22. I every time spent my half an hour to read
    this web site’s content everyday along with a cup of coffee.

  23. thanks thanks so much ^^

  24. thanks a lot ………

  25. After exploring a number of the articles on your blog, I honestly like your technique of blogging.
    I book marked it to my bookmark site list and will be checking back in the near future.

    Take a look at my web site too and let me know what you think.
    Ashley and grow your sociable existence.

    Ashley can considerably improve your relevance in addition to believability.

    Clients can easily Ashley via dozens of affordable providers.

  26. Really userfull article nice job… thanks a lot

  27. Is this Code Works For u…. because Binary() doesnt take parameters…..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com