第一种:可以直接进行写入,代码如下:
[c-sharp] view plaincopyprint?
public static byte[] GetBytesByImage(PictureBox pb)
{
byte[] photo_byte= null;
if (!pb.Image.Equals(null))
{
using (MemoryStream ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(pb.Image);
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
photo_byte = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
bmp.Dispose();
}
}
return photo_byte;
}
第二种:首先将照片转化为byte[]类型,然后在写入数据,代码如下;
[c-sharp] view plaincopyprint?
public static byte[] GetBytesByImagePath(string strFile)
{
byte[] photo_byte = null;
using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
photo_byte = br.ReadBytes((int)fs.Length);
}
}
return photo_byte;
}
第三种:直接读取byte[]并转化为图片;
[c-sharp] view plaincopyprint?
public static Image GetImageByBytes(byte[] bytes)
{
Image photo = null;
using (MemoryStream ms = new MemoryStream(bytes))
{
ms.Write(bytes, 0, bytes.Length);
photo = Image.FromStream(ms, true);
}
return photo;
}
1. 写入数据库
[c-sharp] view plaincopyprint?
public static byte[] GetBytesByImage(PictureBox pb)
{
byte[] photo_byte= null;
if (!pb.Image.Equals(null))
{
using (MemoryStream ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(pb.Image);
bmp.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
photo_byte = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_byte, 0, Convert.ToInt32(ms.Length));
bmp.Dispose();
}
}
return photo_byte;
}
2.将实际位置中的照片转化为byte[]类型写入数据库中;
[c-sharp] view plaincopyprint?
public static byte[] GetBytesByImagePath(string strFile)
{
byte[] photo_byte = null;
using (FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
photo_byte = br.ReadBytes((int)fs.Length);
}
}
return photo_byte;
}
3. 读取byte[]并转化为图片。
[c-sharp] view plaincopyprint?
public static Image GetImageByBytes(byte[] bytes)
{
Image photo = null;
using (MemoryStream ms = new MemoryStream(bytes))
{
ms.Write(bytes, 0, bytes.Length);
photo = Image.FromStream(ms, true);
}
return photo;
}
将byte[]的值存入数据库,需要数据库表中对应字段的数据类型为Image
编写ado代码访问数据库时需要用到命名参数,且将这个参数的值赋值为你想插入数据库的byte[]的值即可
using (SqlConnection conn = new SqlConnection(sqlconnstr))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into T_Img(imgfile) values(@imgfile)";
SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
par.Value = bt;
cmd.Parameters.Add(par);
int t=(int)(cmd.ExecuteNonQuery());
if (t > 0)
{
Console.WriteLine("插入成功");
}
conn.Close();
}
//par.Value = bt;中的bt就是你的那个数据byte[]