读书人

c# 图片转换成二进制二进制转换成图

发布时间: 2012-10-25 10:58:58 作者: rapoo

c# 图片转换成二进制,二进制转换成图片
我想把图片转换成二进制存到数据库里

[解决办法]
大概是这样的

Image _Image = Image.FromFile(@"C:\1.jpg");

System.IO.MemoryStream _ImageMem = new System.IO.MemoryStream();
_Image.Save(_ImageMem, ImageFormat.Bmp);
byte[] _ImageBytes = _ImageMem.GetBuffer();
//获取流 这里其实应该是直接用文件方式获取..如System.IO.File.ReadAllBytes(@"C:\1.jpg")

SqlCommand _SqlCommand = new SqlCommand("Insert into ImageTable(name,image)values(@name,@image)");
_SqlCommand.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar, 20));
_SqlCommand.Parameters.Add(new SqlParameter("@image", SqlDbType.Image));

_SqlCommand.Parameters[0].Value = "ImageName";
_SqlCommand.Parameters[1].Value = _ImageBytes;
执行这个SQLCOMMAND
[解决办法]

C# code
    public static class BitmapHelper    {        public static Bitmap BytesToBitmap(byte[] Bytes)        {            MemoryStream stream = null;            try            {                stream = new MemoryStream(Bytes);                return new Bitmap((Image)new Bitmap(stream));            }            catch (ArgumentNullException ex)            {                throw ex;            }            catch (ArgumentException ex)            {                throw ex;            }            finally            {                stream.Close();            }        }        public static byte[] BitmapToBytes(Bitmap Bitmap)        {            MemoryStream ms = null;            try            {                ms = new MemoryStream();                Bitmap.Save(ms, Bitmap.RawFormat);                byte[] byteImage = new Byte[ms.Length];                byteImage = ms.ToArray();                return byteImage;            }            catch (ArgumentNullException ex)            {                throw ex;            }            finally            {                ms.Close();            }        }    }
[解决办法]
C# code
//保存图片:                    SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=;database=master");                  conn.Open();                  SqlCommand cmd = new SqlCommand("insert into image values(@i)", conn);                  byte[] ib = new byte[60000];                  FileStream fs = new FileStream(this.openFileDialog1.FileName.ToString(), FileMode.Open, FileAccess.Read);                  fs.Read(ib, 0, 60000);                  cmd.Parameters.Add("@i", SqlDbType.Image, (int)fs.Length);                  cmd.Parameters["@i"].Value = ib;                  cmd.ExecuteNonQuery();                  conn.Close();                  MessageBox.Show("保存成功");  //显示图片:               SqlConnection conn = new SqlConnection(@"data source=.;uid=sa;pwd=;database=master");              conn.Open();              SqlCommand cmd = new SqlCommand("select image1 from image", conn);              SqlDataReader reader = cmd.ExecuteReader();              reader.Read();              while (reader.Read())              {                  for (int i = 0; i  < reader.FieldCount; i++)                  {                      MemoryStream buf = new MemoryStream((byte[])reader[i]);                      Image image = Image.FromStream(buf,true);                      this.pictureBox1.Image = image;                  }              }
[解决办法]
1.任何文件以二进制存入Access数据库:
……
if (opFlDlg.ShowDialog() == DialogResult.OK)
{
Stream fl = null;


byte[] flArr;
string flext;
if ((fl = opFlDlg.OpenFile()) != null)
{

flArr = new Byte[fl.Length];
flext = Path.GetExtension(opFlDlg.FileName);
fl.Close();

String cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\数据库.mdb";
OleDbConnection cnn = new OleDbConnection(cnnStr);
try
{
cnn.Open();
OleDbCommand cmd = new OleDbCommand("select * from CSDoc", cnn);
DataSet ds = new DataSet();
OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
dap.Fill(ds, "CSDoc");
DataRow dr = ds.Tables["CSDoc"].NewRow();
dr["docindex"] = int.Parse(xh);
dr["doctitle"] = ttl;
dr["doccontent"] = "";
dr["doctwos"] = flArr;
dr["lang"] = flg;
dr["cclx"] = 3;
dr["kzm"] = flext;
ds.Tables["CSDoc"].Rows.Add(dr);
OleDbCommandBuilder cb = new OleDbCommandBuilder(dap);
dap.Update(ds, "CSDoc");
MessageBox.Show(" 磁盘文件保存成功!");
}
catch (OleDbException ee)
{
MessageBox.Show(ee.Message);
}
}
else
{
MessageBox.Show(" 文档打开不成功。");
}

2.读出二进制数据还原成文件:
{ …… }
System.Diagnostics.Process opPro = null;
ClslinkMDB toHSlst = new ClslinkMDB(); //ClslinkMDB 是自己写的数据库操作类
toHSlst.connStrings = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\数据库.mdb";
sqls = "select doccontent,doctwos,cclx,kzm from CSDoc where [ID]=" + theID;
OleDbDataReader theRD = toHSlst.SqlToOlySet(sqls);
theRD.Read();
byte[] memArr = null;
String kzmStr = theRD["kzm"].ToString();
String flnm = "~~~~" + kzmStr;
memArr = (byte[])theRD["doctwos"];
try
{
if ((opPro != null) && (!opPro.HasExited))
{
opPro.CloseMainWindow();
}
File.WriteAllBytes(flnm, memArr);
opPro = System.Diagnostics.Process.Start(flnm);
}
catch (SystemException ee)
{
MessageBox.Show(ee.Message + ee.Source);
}
-----------------------------------------------------

这是在我的一个小程序里的代码。如要下载:http://download.csdn.net/source/901579

读书人网 >C#

热点推荐