Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Image Manipulation using LINQ to SQL from ASP.Net Application

Image Manipulation using LINQ to SQL from ASP.Net Application

In this article, I am going to show you How to insert an image from ASP.Net application to SQL Server using LINQ to SQL and how to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.

Author Rank :
Page Views : 11816
Downloads : 232
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
uploadingImageusingLInqtoSQl.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Objective

In this article, I am going to show you How to insert an image from ASP.Net application to SQL Server using LINQ to SQL and how to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control.

Block Diagram of solution

figure1.gif

Description of table


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

figure2.gif

  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

figure3.gif

Saving image in table

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

figure4.gif

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.

figure5.gif

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.

figure6.gif

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

figure7.gif

figure8.gif

figure9.gif

For your reference Source code is given as below

Default.aspx.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data.Linq;
using System.IO;

namespaceuploadingImageusingLInqtoSQl
{
publicpartialclass_Default : System.Web.UI.Page
    {
protectedvoidPage_Load(object sender, EventArgs e)
        {

        }

protectedvoid Button1_Click(object sender, EventArgs e)
        {
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
            {
stringfileName = FileUpload1.FileName;           

byte[] fileByte = FileUpload1.FileBytes;
BinarybinaryObj = newBinary(fileByte);
DataClasses1DataContext context = newDataClasses1DataContext();
context.ImageTables.InsertOnSubmit(
newImageTable { Id = "xyz",
                        Name = fileName,
FileSource = binaryObj });
context.SubmitChanges();

            }
        }

protectedvoid Button2_Click(object sender, EventArgs e)
        {

            Image1.ImageUrl = "~/MyPhoto.ashx?Id="+TextBox1.Text;

        }

    }
}

MyPhto.ashx.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
using System.IO;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespaceuploadingImageusingLInqtoSQl
{
///<summary>
///
Summary description for MyPhoto
///</summary>
publicclassMyPhoto : IHttpHandler
    {

publicvoidProcessRequest(HttpContext context)
        {

string id = context.Request.QueryString["Id"];
context.Response.ContentType = "image/jpeg";
Streamstrm = ShowEmpImage(id);
byte[] buffer = newbyte[4096];
intbyteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq> 0)
            {
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
            }  
        }

publicStreamShowEmpImage(string id)
        {
DataClasses1DataContext context1 = newDataClasses1DataContext();
var r = (from a in context1.ImageTables wherea.Id == id select a).First();
returnnewMemoryStream(r.FileSource.ToArray());         
 
        }
publicboolIsReusable
        {
get
            {
returnfalse;
            }
        }
    }
}

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

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
I write few articles on Microsoft technologies. Read my blog at . | Mincracker MVP | Microsoft MVP
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Upload image from detailsview by juan On January 31, 2011
How can I do the same have you explain but from a DetailsView? Thank you very much in advance.
Reply | Email | Modify 
Interesting by Charles On February 12, 2011
I really enjoy this article, it just worked perfectly. Thanks a thousand times
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.