How to convert image to byte array

前端 未结 12 1595
悲哀的现实
悲哀的现实 2020-11-22 09:52

Can anybody suggest how I can convert an image to a byte array and vice versa?

I\'m developing a WPF application and using a stream reader.

12条回答
  •  余生分开走
    2020-11-22 10:48

    This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk

     public void SavePicture()
        {
            SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
            SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
            SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
            DataSet ds = new DataSet("tablename");
            byte[] MyData = new byte[0];
            da.Fill(ds, "tablename");
            DataTable table = ds.Tables["tablename"];
               for (int i = 0; i < table.Rows.Count;i++ )               
                   {
                    DataRow myRow;
                    myRow = ds.Tables["tablename"].Rows[i];
                    MyData = (byte[])myRow["Picture"];
                    int ArraySize = new int();
                    ArraySize = MyData.GetUpperBound(0);
                    FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(MyData, 0, ArraySize);
                    fs.Close();
                   }
    
        }
    

    please note: Directory with NewFolder name should exist in C:\

提交回复
热议问题