Hi, I saw many developers are asking this questions in different forums. Recently I saw this question on MSDN forum and I thought let me write a blog on this. I know many of us found this too easy however for new bees its bit hard.
In this article, I had used SQL Server 2005 as back end and C# as front end. SQL Server has “Image” data type to store the image. In Oracle and some other database you can use a data type which is used to store binary value (may be BLOB). I have created a simple aspx which has File upload control and a button. When user selects a file to upload, I am checking it for valid image type and converting it to array of Bytes. Then I will store that byte array into database. Below is the code,
if (objFileUpload.PostedFile !=null)
{
if (objFileUpload.PostedFile.ContentLength > 0)
{
// Get Posted File.
HttpPostedFile objHttpPostedFile = objFileUpload.PostedFile;
// Check valid Image type. Create this function according to your need
if (CheckValidFileType(objHttpPostedFile.FileName))
{
// Find its length and convert it to byte array
int intContentlength = objHttpPostedFile.ContentLength;
// Create Byte Array
Byte[] bytImage =new Byte[intContentlength];
// Read Uploaded file in Byte Array
objHttpPostedFile.InputStream.Read(bytImage, 0,
intContentlength);
}
}
}
Fig – (1) Read Uploaded file (here Image) in Byte Array
Pass this Byte array to you DAL and use it for storing image in database. I am using Enterprise Library as DAL so my code will look like,
Database db =DatabaseFactory.CreateDatabase();
string sqlCommand =“StoredProcedureName”;
DbCommand dbCommandWrapper = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(dbCommandWrapper,“@Image”,DbType.Binary,
bytImage );
try
{
db.ExecuteNonQuery(dbCommandWrapper);
}
catch {throw; }
Fig – (2) Insert Image in to database
This is how you can store the Image in database. Retrieving the image is the same process. Write a SP which will return your image. Store this value in a Byte Array. Once you get the image in Byte array, you just have to write it on form as shown below,
Byte[] bytImage =Byte array retrieved from database.
if (bytImage !=null)
{
Response.ContentType =“image/jpeg”;
Response.Expires = 0; Response.Buffer =true;
Response.Clear();
Response.BinaryWrite(bytImage);
Response.End();
}
Fig – (3) Code to display Byte array as Image on form.
To use this at multiple places in your application, you create a page to which you can pass ID of Image and it will retrieve image from database and create image. To do this copy paste above code in aspx.cs file. Now on every page you require to show this image take <asp:Image> on that page and set its ImageURL property to the path of newly created user control. See the code below,
<asp:Image ID=”ViewImage” runat=”server” />
Fig – (4) Image control on any aspx page (Lets say Sample.aspx).
string strURL =“~/ViewImage.aspx?ID= 1 “ ;
ViewImage.ImageUrl = strURL;
Fig – (5) Set Image URL for image control on code behind (Sample.aspx.cs)
You can see the image will be displayed in your page where you had put Image tag.
Happy Programing.
Thanks! This was a perfectly simple example to get me started.
I am storing the byte array directly into image type column by insert statement.
Iam retriving the cells of image type from dataset
as
byte[] buffer=null;
DataSet dsetAttachment;
// Retrive attachment table data in the dataset
buffer=(byte[]) dsetAttachment.Tables[0].Rows[0]["Attachent"];
*attachments is the name of column of image datatype
*indexing is also proper as i have cheked it thru debugging
But from the above C# statement only 13 bytes are coming into the byte array and the file alwayz consist of text “System.byte[]” which is nothing but the type of variable used above .
Can u tel where am i mistaken
Amit,
Change this line
byte[] buffer=null
buffer=(byte[]) dsetAttachment.Tables[0].Rows[0][”Attachent”];
by
Byte[] buffer=null;
buffer=(Byte[]) dsetAttachment.Tables[0].Rows[0][”Attachent”];
This may solve the issue.
I want submit image into Sql table through com component in ASP
Is it prosibble tell me how to insert byte array directly into image type column by insert statement.
Thanks
This is great. I set mine up so it would call another page to load the images but found I got an error
“Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”
This was caused by the
Response.End();
Even though the page loaded all the pictures fine it still passed through the ‘catch’ as an error. So to fix this I replaced this with:
HttpContext.Current.ApplicationInstance.CompleteRequest
..and no more error.
http://support.microsoft.com/kb/312629/EN-US/
Here is what I had…
My datalist code…
‘ Runat=server />
Calls…..
public string FormatURL(object _id)
{
int num = Convert.ToInt32(_id);
return (“~/GetImage.aspx?id=” + _id);
}
The GetImage.aspx code…..
int IDImage = Convert.ToInt32(Request.QueryString["ID"]);
try
{
if (connect.State != ConnectionState.Open)
connect.Open();
if (IDImage > 0)
{
cmdGet = new System.Data.SqlClient.SqlCommand();
cmdGet.CommandText = “SELECT FileData FROM AssetImages WHERE AssetImageID = ” + IDImage + “”;
cmdGet.Connection = connect;
GetImg = (byte[])cmdGet.ExecuteScalar();
Response.ContentType = “image/jpeg”;
Response.Expires = 0;
Response.Buffer = true;
Response.Clear();
Response.BinaryWrite(GetImg);
//Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
catch (Exception ex) { }
finally
{
connect.Close();
}
}
By the way if you want to compress files before they are saved to the DB try this…
http://www.imageoptimizer.net/pages/?page=Download
Just add the resource to your project. Add it to your tool box and drag it onto your form. Set your properties.
This will optimize it….
fileDetail container = new fileDetail();
this.FileData = this.imgOpt.Optimize(pf);
NOTE: FileData is a Byte array
Sorry the small section
My datalist code…
‘ Runat=server />
…was cut off. This site may not encode html characters…
basically, I use a datalist and in the ItemTemplate I inserted an asp image control. the imageURL is
FormatURL(DataBinder.Eval(Container.DataItem, “AssetImageID”))
…this calls the method above in my last script. So thats what was left out sorry. Note: Be sure to bind to your database and ‘AssetImageID’ is just the field I have my unique ID in yours may be different.
One last thing….
The dll you can download for optimizing your code is very simple but the example I left (again) was missing stuff…
try
{
//Get the file
HttpPostedFile pf = this.FileUpload1.PostedFile;
if (pf.ContentLength != 0)
{
container.FileData = this.imgOpt.Optimize(pf);
…etc (get file name, type, size), create your Sql params, command, connection, and execute…bla bla.
Very cool. This little dll will ensure that file sizes are managed!!
Hi iam a newbie to dotnet
i used this code 2 display image
byte[] image = (byte[])cmd.ExecuteScalar();
MemoryStream str = new MemoryStream(image);
Response.ContentType = “image/jpg”;
Bitmap bmp = new Bitmap(str);//convert memorystream 2 a bitmap
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
It works but only image is shown on the webpage all other were unseen.
Can u help me??
Asif,
I am not able to understand the last line “It works but only image is shown on the webpage all other were unseen.”.
Can you please let me know where else you want to show that image?
chiragrdarji,
i am using to store images for new employees and i want to display image as their profile image like in orkut etc,
if u know please forward code to banda.sai@gmail.com
Hi,
This information was very useful for my application. It is really a fantastic code.
Thank you
Lakshmanarayanan
Chirag,
This infn really helped me.
Thanks,
——————-
Keyur Vachhani
First of all nice article i liked it.
I want to store byte array in table, but i want to store that
information with simple insert query but i don’t know how to insert that in query
Sample code
dim byteArrValue() as Byte
SQL = “INSERT INTO TEMP (TEMP_NAME,TEMP_BINARYDATA) VALUES (“sandesh”, ???????? )”
How should i pass byte array “byteArrValue” in query at ??????.
Thank you in advance.
Saandesh,
Here is your solution.
using (SqlConnection cnn = new SqlConnection(“Server=dotnet-server;database=magnifi;uid=sa;password=Cygnet@123;”))
{
cnn.Open();
Byte[] obj = new Byte[100];
string sql = “insert tblTempQuestionImage (QuestionImage) values (@Imag)”;
SqlCommand cmd = new SqlCommand();
SqlParameter sp = new SqlParameter(“@Imag”,SqlDbType.Binary);
sp.Value = obj;
cmd.Parameters.Add(sp);
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
}
Hello,
I’m using the same concept of storing the content of the (.doc, .rtf, .pdf, etc) in the “image” column of the SQL Server as you have explained for the image type. (refered some online articles)
Now once i retrieve it from the database, the byte[] return only 13 bytes. I saw a post where you have mentioned to change the byte[] with Byte[], I even tried that also. Its not working.
Can you kindly help me on this??
Anyone knowing the solution can post me on keerthi.bhatt@gmail.com
Regards
Keerthi
I’m Display the image from sql server 2005 using this code.
Is it possible to display it in a image button? Give me any sample.
Dim myDataReader as SqlDataReader
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
Do While (myDataReader.Read())
Response.ContentType = myDataReader.Item(“PersonImageType”)
Response.BinaryWrite(myDataReader.Item(“PersonImage”))
Loop
Muthunagai,
You need to create a page “testImage.aspx” page. In that page you need to pass Image ID as query string. Depending on that ID you have to get the Image from database and have to write
Response.BinaryWrite(myDataReader.Item)
On Main page where you have image button, you can set ImageURL property of that button to “testImage.aspx?ImageID=1″ page.
This will solve your issue.
Thank You!
Thanks! This is exactly what I was looking for when doing a Google search. Thank you so much for taking the time to write this is a very straight-forward, and easy to read manner.
having the same problem about 13 bytes. anyone have any solutions??
Benjamin & Asif,
Can you send me the code and sample file which you used for storing and retrieving? I may helped you by looking in to your code and files.
hello chiragrdarji! (:
thank god, you are on the way of saving my life. im talking about a final year proj thatt i m working on. and im like so dead on how these inserting of images to sql server 2005 actually works. until, i found your page. hooray for that! at last, i have a greater understanding on this.
however, your code is based on a .asp right? so i am quite blur on how i can apply your codes to my application.
im using Visual Studio 2005, to do my windows application on a C# platform. and sql server 2005. i want the pictures to store in the database. and retrieve it on the datagridview. (:
so how can i go about doing this?
Excellent – this will help me greatly with my porn network – what happened to your fingers by the way?
EXCELENT work Chiragrdarji with that Storing and Retrieving Image in SQL Server article!!!!!
greenappleee,
In search of the same solution to an application storing
binary files (zip) I came up with a solution for all.
Db Type = Image
create stored procedure (or query)
select filename, filebinary, datalength(filebinary) as binaryLength
from files
//in code:
int length = int.Parse(row["binaryLength"].ToString())
byte[] catBytes = (Byte[])row["FileBinary"];
using (System.IO.FileStream sw = new FileStream(ofDiag.FileName, FileMode.Create, FileAccess.Write))
{
sw.Write(catBytes, 0, length);
sw.Flush();
}
Thnks for poting solution.
Hi there Chiragrdarji,
I am wrinting you again becuase I have a doubt and I will appreciate any help that you can provide me with.
I am working in .NET 2.0, with C# and this is my situation: I have a form with some info about a client (First Name, Lasta Name, Birthday,…,Picture). The last info is the user’s photo, that is, it is an image and for that reason I am using an control. The problem is that I do not know how to assign the file content into the control once I retrieve the user’s photo from the database.
I did what you suggested about creating a new .aspx page in which PageLoad event one has to get the image from the database and send it out through Response.BinaryWrite(aImage) fucntion call. I assigned this .aspx page in the ImageUrl property of the Image object that I am using in the other .aspx page (the one that I mentioned at the begining to show the user’s info) to visualize the User’s photo.
What it is wrong with that?
Another way of implementing the same stuff?
Thanks in advance,
Madrazo
Hi Madrazo,
Can you send me the code which is not working? May be I can help you.
Hi chiragrdarji,
Thanks for your offer to help me out.
This is what i have in the code behind for one of my pages. The one with a button that is supposed to load the image that is stored in the database once it is clicked (the procedure receives as a parameter the ID of the image to load):
protected void B_LoadImage_Click(object sender, EventArgs e)
{
if (this.TB_FileID.Text.Length > 0)
{
//Getting the connection string from the web.config
string sConnStr = ConfigurationManager.ConnectionStrings["Sql2000ConnectionString"].ConnectionString;
//Sql statement
string sSQL = “SELECT FileID, FileName, FileLength, FileContent FROM _File WHERE FileID = ” + this.TB_FileID.Text;
try
{
//Creating Connection to database
using (SqlConnection oSqlConnection = new SqlConnection(sConnStr))
{
SqlCommand oSqlCommand = new SqlCommand();
oSqlCommand.Connection = oSqlConnection;
oSqlCommand.CommandText = sSQL;
oSqlConnection.Open();
//Query Execution
try
{
SqlDataReader oSqlDataReader = oSqlCommand.ExecuteReader();
if (oSqlDataReader.Read())
{
TB_FileName.Text = (string)oSqlDataReader["FileName"];
TB_FileSize.Text = oSqlDataReader["FileLength"].ToString();
I_File.ImageUrl = “~/LoadAnImage.aspx?ImageID=” + this.TB_FileID.Text;
}
this.L_Error.Text = “File was already Loaded from the database”;
}
catch (Exception oException)
{
string sM = oException.Message;
}
finally
{
oSqlConnection.Close();
}
}
}
catch (Exception oException)
{
string sM = oException.Message;
}
}
}
As you can see in the control (I_File) the ImageUrl property is set to “~/LoadAnImage.aspx?ImageID=” + this.TB_FileID.Text
That is, it calls a page for which only the Page_Load event was coded as follows:
protected void Page_Load(object sender, EventArgs e)
{
int nImageID = 0;
if (Request.QueryString["ImageID"] != null)
nImageID = System.Convert.ToInt32(Request.QueryString["ImageID"]);
if (nImageID != 0)
{
//Getting the connection string from the web.config
string sConnStr = ConfigurationManager.AppSettings["Sql2000ConnectionString"];
//Sql statement
string sSQL = “SELECT FileContent FROM _File WHERE FileID = ” + nImageID.ToString();
try
{
//Creating Connection to database
using (SqlConnection oSqlConnection = new SqlConnection(sConnStr))
{
SqlCommand oSqlCommand = new SqlCommand();
oSqlCommand.Connection = oSqlConnection;
oSqlCommand.CommandText = sSQL;
oSqlConnection.Open();
//Query Execution
try
{
oSqlCommand.ExecuteReader();
SqlDataReader oSqlDataReader = oSqlCommand.ExecuteReader();
//Since the image data is binary data, it was used Response.BinaryWrite
//instead of normal Response.Write
if (oSqlDataReader.Read())
{
Response.ContentType = “image/gif”;
Response.BinaryWrite((byte[])oSqlDataReader["FileContent"]);
}
}
finally
{
oSqlConnection.Close();
}
}
}
catch (Exception oException)
{
string sM = oException.Message;
}
}
}
So, that’s it Chirag Darji. I hope that that info is enough for you to realize what is missing in my code. Remind that I want to visualizein an control an image that is stored in the database.
Thanks in advance again,
Madrazo
!Thanks to you dear Madrazo, I was searching for the solution for last 10 days and found here in your post, keep growing and sharing….God Bless You!
Hi there again chiragrdarji,
A couple of lines just to tell you that I just found the mistake. I had not realized that I was calling the ExecuteReader function twice and unfourtunately I forgot to use add a catch block to detect a error in that part of my code. Now it is working well.
Thanks once more man and keep posting those very useful tips.
Regards,
Madrazo
Hi,
Inserting and retrieving images is somewhat easy. Can you tell me how to retrieve any binary data (Documents, pdf file etc) from the database? The files are stored in a table as image fields. I mean they are converted in to binary data and then inserted in to the datbase. How to retrieve them and store them in to client computer. I’m using asp.net with C#.I’ve been searching solution for this problem from the last 10 days.
Thanks,
Kiran
Amit and Kithi and Kiran,
Here is my new post for your solution.
http://chiragrdarji.wordpress.com/2007/08/31/storing-and-retrieving-docpdfxls-files-in-sql-server/
Hi all,
i would like to retrive image from sql server into gridview. i cant get the image on grid view…
can u help me how to get it? i stored image in sql as image datatype
Prabhakar,
You can create one user control which will load the image from database once image id is given to it. You have to place that user control inside your gridview in TemplatField.
I hope this will help you.
how to pass Null value to image datatype from .net to sqlserver2000 plz help its urjent
hi to all,
I am creating travel project, i want to insert image path in sqlserver rather then image in sqlserver,and i want to display image in the datagridview,
if any one knows just sought my problem,its very urgent
thank you
raghu
hi..
i tried to load image the way u said..
but it didnt fire any error and didnt load the image too..
so i set the viewimage.aspx as start up page and trying to run…
then the following error is firing…
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
and says..
An invalid character was found in text content. Error processing resource
so will suggest me that what might be the error..
shubha
hi..
hey that problem was sorted.. and now its displaying the image.. so now i have changed the startup page…
and running the project..
but its still not displaying the image..
i have written the below code(fetching from database) in viewimage.aspx page in both page_init and page_load events..
Byte[] bytImage =Byte array retrieved from database.
if (bytImage !=null)
{
Response.ContentType =“image/jpeg”;
Response.Expires = 0; Response.Buffer =true;
Response.Clear();
Response.BinaryWrite(bytImage);
Response.End();
}
but am doubtfull that in which event i have to write the above code so that it will work…
or else plz suggest what might be the problem that its not working..
shubha
hi
thanku for yur code, next thing is i want to display the image in datagridview can u please explain me ..
thank you
raghu
Raghu,
You can achieve this by adding obe TemplateField (for VS 2003 TemplateColumn). You need to take one template field and in ItemTemplate you have to take image control. You have to write the code to assign ImageURL to that image control in RowDataBound event. If you are storing image path in SQL sever than you can directly assign that image path to image control. If you are storing the actual image in database you can go for the approach mentioned in Fig -4 and Fig -5 in this article above.
Hope this will help you.
Every thing works fine in .Net, however i wanted similar function in ASP, please help///
I want to save image into MsAccess database.
Need Help.
I want save and retrive image into sql table
Help me
Shishir,
The code mentioned in this article does the same thing.
hi!
i am trying to recover a binary data of textfile. The data has been taken out in a DataReader. I want to display this data in a textbox and not as a Reponse object of the form.
Kindly help me how to do this
hai,
am using asp with c#.net and sqlserver2005 and with no stored procedures.
so please tell me how to insert the images as bytes into database,(*am using just a fileupload control and a button*)
kindly help me.
The FileUpload control is not supported inside an UpdatePanel?
hii chirag.
i m using asp.net 2.0 n c#. and sql server 2000. i want to store image in database n retrieve it in grid view or datalist view.
my database structure is:
my_db
{
prodid varchar(10), // to store id product
description varchar(50),
qty int(4),
image ??????}// * used to store image WHAT SHOULD BE DATATYPE THERE??*/
n how do i store image der? n how to retrieve the same in grid view along with other fields?
Sos un capo, apu!!!!
thanx chirag…
good help.
can u give me suggestion?
what if instead response.binarywrite, i want to assign that to some image object?
Madhvi,
You can do that by the way I suggested in Fig – (5). I do not have any other option redy right now.
hi chirag,
i tried retreiving the image but there’s an exception at the line
Response.BinaryWrite(bytImage);
theres Argument out of range exception.
pls help me.
Hi,
I am trying to store some images in the database sql 2005, wich is part of my questions table. I want to retrive them with the questions and put them at a proper place on my mobile web form.
Can u help me with that?
I am new to sql well I have used it for some time now but I have never used images……
Sonu
i want storing and retrieving images into sqlserver2003 table
using asp.net1.1 using C#language with out strored procedures
hi,
how about the code in VB? Can u give me the vb code for storing and retrieving images into SQLServer 2000?
TQ
Hi!, What about a thumbnail? How could I make a thumbnail? Could u give me an idea?
Mario San,
Below is the link from where you can get the code for generating thumbnail images,
http://chiragrdarji.wordpress.com/2007/08/08/generate-thumbnail-image-in-dotnet/
hey ,
i have this grid in which i want to retrieve an image stored in my SQL 2005 into my web page , its basically a report grid so i used a SQLdataSource but when i add an image field in it i used the field name but i dont know hwat to put in “DataimageURLformatstring” so wheni run my Page all what i get is the Pic with an (X) “pic cant be displayed”
Thank you so much for your help
Lina
Hi,
I keep getting this error do you know what can be causing it.
The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
An invalid character was found in text content. Error processing resource
please dost help me i try loat.but how to retrive image from database i dont no.
Hi,
I am new to SQL Server and Visual Studio…
I having images stored in an sql 2005 table and I would like to display the image in a report created by Visual Studio 2005. How do I do it?
hi i want to store the actual imagei itself in to sqlserver 2005
and retrive the image ……
how can u pls provide some sample code..
Thanks…
thanks..
Hi,
I have a defect tracking tool call testtrack pro which is using Sql server as a database. For the defects which have the attachments these a attachements are being stored in the database in a table called attachement as a image file. when i do select * from attachment iam getting data in this format
ixattachment sdata
1 0×45fsdfkw34mjkhkj3434k234kjbjb3kj
2 lkqwedlksdlks3429342rjn4rn2n123nm3
Is there a way i can download all the attachments with their original names to my local machine.
Please provide me a code or a macro for doing this.
Thanks,
Raj
Hello,
I have problems displaying the image in the webpage, i used a webservice to store the filebytes (property from as:pfileupload) in the image field (i hope is enough)
anyway the image is not displayed (loaded?) in my page when i do this
if (tc.Bytes != null)
{
byte[] Buffer = tc.Bytes;
Response.ContentType =”image/GIF”;
Response.Expires = 0;
Response.Buffer =true;
Response.Clear();
Response.BinaryWrite(Buffer);
Response.End();
}
Please help me! Thanks!
HOW TO Display AN Image’s from an Access Database using VB.NET.
HOW TO Display AN Image’s from an Access Database using VB.NET
I want to save image into MsAccess database.
Need Help.
Hi,
I am storing and retriving the Image in binary form.It had to show on webpage. But I need to show image in TABLE. please someone help me……
Thank’s
i am receiving an error specified cast is not valid
Dim img As Byte() = CType(cmd.ExecuteScalar(), Byte())
i want to retrieve an image stored in sql server 2000 and make it display in an image control when the form loads… how could i do that…> help me…
Thanks in advance
Can anyone help me ——–I need to store all types of images (photos, .doc fils, .pdf files, images, scanned pictures etc.)and display into a frame in the VB 6 forms. I am using MS Access database (ADODB connectivity) to store information, Now i want to write a sql qurey to display any picture saved in my computer into the form (using command button).
I donot want to give the path name in the access database, i want a query to read the bytes of picture and display it in the frame of VB 6 forms.
Pl. i need it ASAP.
Can anyone help me ——–I need to store all types of images (photos, .doc fils, .pdf files, images, scanned pictures etc.)and display into a frame in the VB 6 forms. I am using MS Access database (ADODB connectivity) to store information, Now i want to write a sql qurey to display any picture saved in my computer into the form (using command button).
I donot want to give the path name in the access database, i want a query to read the bytes of picture and display it in the frame of VB 6 forms.
Pl. i need it ASAP.
u can send it to my mail — gar_129@yhaoo.co.uk
Hi,
I tried, writing a stored procedure for the same,
using Textcopy/F command…Its updating the field with some hexa decimal number..instead of the file content…how to proceed now?
jyothi
Hi
// Following code for windows application
public void SqlBlob2File(string DestFilePath)
{
try
{
int PictureCol = 0; // the column # of the BLOB field
SqlConnection cn = new SqlConnection(“server=localhost;integrated security=yes;database=NorthWind”);
SqlCommand cmd = new SqlCommand(“SELECT Picture FROM Categories WHERE CategoryName=’Test’”, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Byte[] b = new Byte[(dr.GetBytes(PictureCol, 0, null, 0, int.MaxValue))];
dr.GetBytes(PictureCol, 0, b, 0, b.Length);
dr.Close();
cn.Close();
System.IO.FileStream fs = new System.IO.FileStream(DestFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(b, 0, b.Length);
fs.Close();
MessageBox.Show(“Image written to file successfully”);
}
catch(SqlException ex)
{
MessageBox.Show (ex.Message);
}
}
I have this in VB.net but its not working
if u can help
** this function i want it to convert Byte() array to System.web.UI.WebControls.Image format
**but it giving me this error.
– pls help me check what the problem is
Private Function ByteToImage(ByVal BImage() As Byte) As Image
Dim theimage As Image
Dim newImage As System.Drawing.Image
Dim ms As MemoryStream = New MemoryStream(BImage, 0, BImage.Length)
ms.Write(BImage, 0, BImage.Length)
theImage = System.Drawing.Image.FromStream(ms, True)
Return theimage
End Function
Hi
I had already stored ith image in system.byte[] form in 1 db.Also m able to retrive it n store it in datatable column of datatype system.byte[] at front end .now my problem is i want to pass the value of column of datatable as parameter of sql thru which i wud hv to store it in another database.i hd tried to many thins but all in vain.Wud u plz help me,i hope u wud.plz try to respond s early s possible .thanks
sqlcon.Open();
SqlDataAdapter sqlda = new SqlDataAdapter(“sp_image”,sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.AddWithValue(“@type”, “S”);
DataSet ds = new DataSet();
sqlda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
above code for retreiving the image that i used but iam unable to convert binary data into object after that i have to bind with grid view
Can u send the possibilities for binding the image into gridview
can you help me store and retrieve image in sql using ASP.net but codes in VB…
Hey Mariel
just visit
http://www.dotnetcurry.com/ShowArticle.aspx?ID=129
and you will get ur solution.
Hi ,
My question is that…
I have brought my picture into new _arrByte array…
for ( i=0; i<5; i++ )
{
Byte[] new_arrByte = (Byte[])objDt.Rows[0]["Picture"];
}
and i have 5 control to bind with…
So how can i set “new_arrByte” with all .
Hi ,
My question is that…
I have brought my picture into new _arrByte array…
for ( i=0; i<5; i++ )
{
Byte[] new_arrByte = (Byte[])objDt.Rows[i]["Picture"];
}
and i have 5 asp:Image control to bind with…
So how can i set “new_arrByte” with all asp:Image.
I know that question doesn’t make scence…
i can do it by creating a *.gif/jpg/bmp files inside the loop using streams and after that Image.ImageUrl = “Createdfilepath”.
But here i just wanted to do so..by avoiding the unneccesary creation of file…
Thanks,
Pankaj Bahuguna….
Hai,
Very gud article.
Expecting more from you.
Thanks & Regards,
Deepak S
hi guys
i dont know if this is the right place to ask. but please help me on how to load and save images in access using visual basic .net 2005
if you like you can send it to my email address at jomarrueco@yahoo.com
thanks…
It is very helpfull. Thanks.
Hi chiragrdarji,
i have a problem with this SQl server.Right now i have a task to create an application about how to retrieve a data from SQL 2005 server using Vb6. Can you show me guideline to do that.
Thank you, Great job explaining this ..saved me much time
hi..
thanks for the code,itz amazing
i tried to load image the way u said..
but it didnt fire any error and didnt load the image too..
so i set the viewimage.aspx as start up page and trying to run…
then the following error is firing…
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.
and says..
An invalid character was found in text content. Error processing resource
application/vnd.openxmlformats-officedocument.wordprocessingml.document
what about this type of file (docx) I keep getting an error when trying to display in browser.
My english language is not good. I need help, i don know how insert image in Sql data base. I’m using Sql Server 2005 and VisualStudio 2008 ASP.NET and C#
HI,
Can anybody let me know how to store image using VB 6.0 in SQL server 2005 and retrieve it to VB forms
Thanks in advance for your help
can i store the image file other than the image data type in sql server……..if so how can i store?…….
and how i retrieve that image in my web application.plz…… give me a solution
Great & simple. Helped me a lot. Thanks.
safda asdf ads asdfasdf
i want to insert the image in a database . after insert the database i want to adept the photo in gridview with using connection.
Hi Chirag,
I really appreciate people like you that share good information.
I’ve implemented your example with regards to uploading and saving any kind of file type (It works great). I’ve also implemented your example for retrieving the file data from the database.
The issue that I’m having is that I can display “jpg”, “bmp”, etc (image) type files with no problem, but when it comes to “doc” or “pdf” files, nothing is being displayed.
I’m assigning the binary data, using the “Response.BinaryWrite” in a “ImageBuild.aspx” page which is the source to ImageUrl of the image control on my “DisplayImage.aspx” page.
I do notice reading thru all the responses that there are others that have experienced a similar issue. Would you by chance have a working example of being able to display the binary data for a MS Word document and/or a PDF document it the appropriate formats?
Thanks once again for great info.
Hi,
Thank you very much for this. Your examples are always help me… (I’m just developing my first web site
TX,
Muditha
how about in the vb6.0 and sql 2005 can you show me some code to save it in the database
Hi thanks for your valuable code, today i will implement your code and test it, i want to see how this code works
Please help!!
I am using this code:
string strSQL = “SELECT * FROM tblI WHERE (ID = ‘20′)”;
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
{
Response.ContentType = “image/jpeg”;
Response.Expires = 0;
Response.Buffer = true;
Response.Clear();
Response.BinaryWrite((byte[])dr["FileData"]);
Response.End();
}
And on webpage all I see is:System.Web.HttpPostedFile
Please help me I am not sure what I am doing wrong
I want to store pdf files and images from front end visual basic to back end SQL server 2005..
It help lot thank you
Hi,
if i wan to save a NULL image to the database(sql-2000),
how can i store it?
Hi Sir,Can any1 help me for resolving that problem.I have a code to store a image in a sql server 2000 using filefiled control in asp and its description with its textbox.
Error is that :- Incorrect syntax near the keyword ‘Values’.
The following code of this page is :-
Imports System.Data.SqlClient
Imports System.Data.SqlClient.SqlTransaction
Imports System.Data
Imports System.Web.UI.Control
Partial Class _Default
Inherits System.Web.UI.Page
Dim con As New SqlClient.SqlConnection
Dim Cmd As SqlClient.SqlCommand
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fileName As String
Dim fileType As String
Dim namePosition As Int16
Dim stream As IO.Stream
stream = FileUpload1.PostedFile.InputStream
Dim uploadedFile(stream.Length) As Byte
stream.Read(uploadedFile, 0, stream.Length)
namePosition = FileUpload1.PostedFile.FileName.LastIndexOf(“\”) + 1
fileName = FileUpload1.PostedFile.FileName.Substring(namePosition)
fileType = FileUpload1.PostedFile.ContentType
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(“INSERT INTO ImageFile (Description, DocumentFileType, DocumentFile, DocumentFileName Values(@Description, @DocumentFileType,@DocumentFile, @DocumentFileName)”, con)
cmd.Parameters.AddWithValue(“@Description”, TextBox1.Text)
cmd.Parameters.AddWithValue(“@DocumentFileType”, fileType)
cmd.Parameters.AddWithValue(“@DocumentFile”, uploadedFile)
cmd.Parameters.AddWithValue(“@DocumentFileName”, fileName)
cmd.ExecuteNonQuery()
con.Close()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
con = New SqlConnection(“Server = server1;uid=sa;pwd =12;database = nitinit”)
con.Open()
End Sub
End Class
please can you make it using visual basic .net of vb6 using sql as database? please help ASAP tnx…
Hi,
i have used a fileupload control in asp.net 2.0 to upload image in SQL SERVER 2005. The code is:
try
{
FileStream fs = new FileStream(FileUpload1.PostedFile.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlCommand com = new SqlCommand(“insert into imageload(imagename) values(@image)”, con);
com.Parameters.Add(“@image”, SqlDbType.Image, image.Length).Value = image;
con.Open();
com.ExecuteNonQuery();
Label1.Visible = true;
Label1.Text = “Image Loaded Successfully”;
}
catch (Exception ex)
{
con.Close();
}
and the code is working very well.now i m trying to retrieve the image on form..plz help
hi
Thanx for code.
I have used your code and
I am getting bytes of stored image,bt it is not displayed in gridview.
plz help
Hi
This is jeevan i need your help to develop my website. My requirement is uploading images path to database and saving uploaded images into physical directory. I am suffering while developing this can you please provide the solution for this
[...] This is a tutorial from very nice Blog: [...]
Hi frds……..Chiragrdaji’s image control tip of including a new aspx page really helped me and also many more frds comments also helped me in many ways……this is really a good discussion i njoyed a lot…….and got enriched may asp.net concepts……
thank you guys….
Hi,
I have seen the procedure for saving image in database using ASP as discussed. Can you show a similar feature using visual basic 6.0?
Amkila.
amkila@yahoo.com
Hi
I want to store .jpg files and images from front end visual basic.net to back end SQL server 2005 and also want to retrive same file.
Which control i use to upload .jpg file.
Hi
I dont want to use stored procedure…….
Hi Mr.chiragrdarji i am gunalan i am a fresher passout in 2009 i just startpreparing .net and i want to know which book is better for startup .net(vb.net & c# .net)
HI
I am using asp.net with c# and sqlserver as back end. I have stored an image in the table. Now i have to retrieve the image when i click a button on the page. Can U please help me with this code.
Hi guys!, thx. a lot!! you save my life. Works perfect. I put the image into a web form and works!.
Than you again.
Saludos desde Mexico.
Hi,
I am new to c#, i encoded a string using ascii encoding and stored it in sql as an image.
Now i want to get that string back in c# for further process, i couldn’t get the exact string as i send,i used following code, please help me.
SqlDataReader dr1 = selCmd1.ExecuteReader();
while (dr1.Read())
{
bytes = (byte[])(dr1["document_content"]);
}
dr1.Close();
string1 = new ASCIIEncoding() .GetString(bytes);
commentTextBox.Text = string1;
Sir, i m Developing gallery releted application
And i want to display image which will change
when somebody press next bottun like any other website
please help me . how i will do this task.
please reply.
regards
Rajeev
The ViewImage.aspx idea was really fantastic and exactly what I was looking for. Thank you very muchChiragrdarji.