C#中将图片转化为byte[]在数据库中存取

来源:互联网 发布:全球淘宝网官方下载 编辑:程序博客网 时间:2024/04/24 00:59

1. 写入数据库:

 

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[]类型写入数据库中:

 

 

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[]并转化为图片:

 

 

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; }

 

原创粉丝点击