1. 程式人生 > >二進制數據將圖片保存到數據庫,並讀取數據庫二進制數據顯示圖片

二進制數據將圖片保存到數據庫,並讀取數據庫二進制數據顯示圖片

returns tco 新建 讀取 指定路徑 stat 指定 字節數 圖片轉換

技術分享

一. 瀏覽圖片

OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"E:\";
ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files(*.*)|*.*";
ofd.RestoreDirectory = true;

if (ofd.ShowDialog() == DialogResult.OK)
{
picAddress = ofd.FileName;
Image imge = Image.FromFile(picAddress);
Bitmap bm = new Bitmap(imge, picBox.Width, picBox.Height);
picBox.Image = bm;
}

二.保存圖片到數據庫

讀取數據庫並取得需要保存圖片的字段,將圖片轉換為二進制數據保存至數據庫中

Byte[] pic = GetContent(圖片的路徑);
Comyindfo.Logo = pic;//數據庫保存的字段

  /// <summary>
/// 將圖片的文件轉化成二進制數據保存到數據庫
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>

public static Byte[] GetContent(string filepath)//將指定路徑下的文件轉換成二進制代碼,用於傳輸到數據庫
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Byte[] byData = new Byte[fs.Length];//新建用於保存文件流的字節數組
fs.Read(byData, 0, byData.Length);//讀取文件流
fs.Close();
return byData;
}

三.從數據庫讀取二進制數據並顯示圖片

byte[] imagebytes = item.Logo;//讀取數據庫的字段
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pictureBox1.Image = bmpt;

二進制數據將圖片保存到數據庫,並讀取數據庫二進制數據顯示圖片