Saturday 15 March 2014

Convert Image To Byte Array in C#

The following code snippet can be used to convert image to byte array.

  protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (FileUpload1.HasFile)
                {
                    Image imag = Image.FromStream(FileUpload1.PostedFile.InputStream);
                    var connection = new SqlConnection(ConnectionString);
                    connection.Open();
                    var sqlCom = new SqlCommand("Insert into SP_ProductsImage (ProductsName, ProductsDescription,ProductsImage) Values (@ProductsName, @ProductsDescription,@ProductsImage)", connection);
                    sqlCom.Parameters.Add("@ProductsName", txtProductName.Text);
                    sqlCom.Parameters.Add("@ProductsDescription", txtDescription.Text);
                    sqlCom.Parameters.Add("@ProductsImage", SqlDbType.Image, 0).Value = ConvertImageToByteArray(imag, ImageFormat.Jpeg);
                    sqlCom.ExecuteNonQuery();
                }
                else
                {
                    Response.Write("<script>alert('Please file upload')</script>");
                }

            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }
        }



  private byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage)
        {
            byte[] bytes;
            try
            {
                using (var ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    bytes = ms.ToArray();
                }
            }
            catch (Exception)
            {
                throw;
            }

            return bytes;
        }


OR

        public static byte[] GetBytesFromFile(string fullFilePath)
        {
            try
            {
                FileStream fs = null;
                fs = File.OpenRead(fullFilePath);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                return bytes;
            }
            catch (Exception exception)
            {
                throw;
            }
        }

Convert Byte Array To Image.


 protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var connection = new SqlConnection(ConnectionString);
                connection.Open();
                var command = new SqlCommand("select * from [AdventureWorks2012].[Production].[ProductRevenue]", connection);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    byte[] imageData = ((Byte[])reader["Image"]);
                    Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(imageData);
                }
            }
            catch (Exception ex)
            {

                Response.Write("<script>alert('" + ex.Message + "')</script>");
            }

        }


1 comment: