Friday, June 10, 2011

Convert image to binary and upload to database using ASP.NET

This article is about uploading images to server/database using ASP.NET. For uploading an image to database ,it has to be first converted to binary format. Then it has to be saved to a database table; the table should have a column with data type [image] for storing the binary image data.

Ok, enough of theory. Let us try out an example.

1) Create a ASP.NET web application using VS2008/2010

2) In default.aspx provide a input control of type “file” and a button

<input type="file" runat="server" id="photoupload" />
<asp:Button runat="server" ID="btnSave" Text="Save" onclick="btnSave_Click"/>

3) Create a function to convert stream to byte[]

public byte[] StreamToByteArray(Stream input)
{
    byte[] total_stream = new byte[0];
    byte[] stream_array = new byte[0];
    byte[] buffer = new byte[1024];

    int read = 0;
    while ((read = input.Read(buffer, 0, buffer.Length )) > 0)
    {
 stream_array = new byte[total_stream.Length + read];
 total_stream.CopyTo(stream_array, 0);
 Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
 total_stream = stream_array;
    }

    return total_stream;
}


4) In the button click event, write code to get the stream from uploaded image and convert to byte array.(Import System.IO- using System.IO;)

Stream oStream = photoupload.PostedFile.InputStream;
byte[] arr = StreamToByteArray(oStream);
oStream.Close();
oStream.Dispose();


5) Now pass the byte[] data to database

SqlConnection oConnection= new SqlConnection("[connectionstring]”);
SqlParameter oParam1 = new SqlParameter("@data", arr);
oParam1.DbType = System.Data.DbType.Binary;
SqlParameter oParam2 = new SqlParameter("@description", photoupload.PostedFile.FileName);

SqlCommand oCommand = new SqlCommand(“[storedprocname]”);
oCommand.Parameters.Add(oParam1);
oCommand.Parameters.Add(oParam2);

oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Connection = oConnection;
oConnection.Open();
int i = oCommand.ExecuteNonQuery();
oConnection.Close();

Done! Now the image is saved in database.

6) Code snippet for getting the binary data back from database is given below

/*Get binary data into dataset*/
DataSet ds = oDal.GetData("[stored procedure name]" + photoid.ToString());

byte[] arr = (byte[])ds.Tables[0].Rows[0]["data"];
MemoryStream oStream = new MemoryStream(arr);
Response.ContentType = "image/png";
Response.BinaryWrite(arr);

2 comments:

Prashobh said...

Image to binary we can do only using javascript also (Client side).
I tried to explain here http://angulartutorial.blogspot.in/2014/03/save-highchart-as-binary-image.html about converting chart to binary .

Unknown said...

The first and easiest way to convert an image to bytes is to use the ImageConverter class under the System.Drawing namespace. The ConvertTo function is not static, so you'll need to create an instance of the class. The function returns an object so the result needs to be converted to the proper type.

public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}