照片的保存與讀取
/// <summary> /// 圖片轉二進制 /// </summary> /// <param name="imgPhoto">圖片對象</param> /// <returns>二進制</returns> public static byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { //將Image轉換成流數據,並保存為byte[] MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; }
調用這個方法把普通轉為2進制,並把它轉成 Base64 形式的 System.String
string s = Convert.ToBase64String(PhotoImageInsert(PictureBox.Image))
轉完之后,剩下的就是保存到數據庫了,這個就是普通的Insert了,倒是要注意字段的長度
讀取圖片並顯示出來:
如何讀取的代碼我就不寫了,相信大家肯定是沒問題的。
//字符串轉二進制
byte[] imageBytes = Convert.FromBase64String(dt.Rows[0]["img_pic"].ToString());
MemoryStream ms = new MemoryStream(imageBytes);
Bitmap bmpt = new Bitmap(ms);
PictureBox.Image = bmpt;
圖片另存
SaveFileDialog.Title = "附件另存"; SaveFileDialog.Filter = "jpg圖片|*.JPG|gif圖片|*.GIF|png圖片|*.PNG|jpeg圖片|*.JPEG"; SaveFileDialog.FilterIndex = 3;//設置默認文件類型顯示順序 SaveFileDialog.RestoreDirectory = true; //點了保存按鈕進入if (picBox1.Image != null) { if (SaveFileDialog.ShowDialog() == DialogResult.OK) { string pictureName = SaveFileDialog.FileName; //照片另存 using (MemoryStream mem = new MemoryStream()) { //這句很重要,不然不能正確保存圖片或出錯(關鍵就這一句) Bitmap bmp = new Bitmap(picBox1.Image); //保存到磁盤文件 bmp.Save(@pictureName, PictureBox.Image.RawFormat); bmp.Dispose(); MessageBox.Show("附件另存成功!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } else { MessageBoxEx.Show("沒有附件信息!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Information); }