圖檔存入資料庫
有時候,有些資料除了文字之外還會有一些圖檔,所以就有一個想法,把圖檔變成一個欄位值也就是一對二進位碼,然後存到資料庫內,需要的時候再把資料取出,回組成圖檔,如此一來就不用文字+圖片分離了。
VB.NET
Dim myPhoto As Byte() = My.Computer.FileSystem.ReadAllBytes(img_FileName)
# img_FileName:圖檔檔名,完整路徑+檔名
# 宣告 myPhoto 為位元
# 資料庫內的欄位要宣告成 <Image>,使用的資料庫是MS-SQL2012。
Dim myphoto As Byte() = rs1("img_Pic") ' 從資料庫內讀出的二進位欄位
Dim MyFile As FileStream '串流
Dim imgFileName As String = "aa.png" ' 要還原的圖檔名稱,要注意副檔名,簡單說不能從存入jpg讀出變成png
MyFile = File.Open(imgFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite) ' 開啟檔案寫入模式
Dim myWriter As BinaryWriter = New BinaryWriter(MyFile) ' 開啟寫入器
myWriter.Write(myphoto) ' 寫入檔案
myWriter.Close() ' 關檔
以下利用讀寫來進行圖檔的複製
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim imgFileName As String = ""
Try
OpenFileDialog1.Filter = "*.png|*.png"
OpenFileDialog1.ShowDialog()
imgFileName = OpenFileDialog1.FileName
Catch ex As Exception
End Try
If System.IO.File.Exists(imgFileName) Then
txt_FileName.Text = imgFileName
PictureBox1.ImageLocation = imgFileName
txt_name_1.Text = System.IO.Path.GetFileName(imgFileName)
txt_name_2.Text = System.IO.Path.GetExtension(imgFileName)
Dim extName As String = System.IO.Path.GetExtension(imgFileName)
Dim myByte As Byte() = image_to_Byte(imgFileName)
PictureBox2.ImageLocation = Save_to_img(myByte, extName)
End If
End Sub
Function image_to_Byte(ByVal img_FileName As String) As Byte()
Dim a As Byte() = My.Computer.FileSystem.ReadAllBytes(img_FileName)
Return a
End Function
Function Save_to_img(ByRef myBytea As Byte(), ByVal extName As String) As String
Dim MyFile As FileStream '串流
Dim imgFileName As String = "aa" + extName ' 要還原的圖檔名稱,要注意副檔名,簡單說不能從存入jpg讀出變成png
MyFile = File.Open(imgFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite) ' 開啟檔案寫入模式
Dim myWriter As BinaryWriter = New BinaryWriter(MyFile) ' 開啟寫入器
myWriter.Write(myBytea) ' 寫入檔案
myWriter.Close() ' 關檔
Return imgFileName
End Function
沒有留言:
張貼留言