先將圖片檔的內容讀入一個 Byte 陣列中,然後使用此陣列來建立一個 MemoryStream 物件。並將此 MomoryStream 物件作為一來源來建立 Image 物件,並將此作為表單的背景圖片 or 放入 PictureBox 中。
(OpenRead 相當於 FileStream)

方法一:

Dim mBinaryAry() As Byte
Dim myImg As Image
Dim fs As IO.FileStream
Try
    fs = IO.File.OpenRead(Application.StartupPath + "\myImg.jpg")
    ReDim mBinaryAry(CInt(fs.Length - 1))

    '用 Read 方法將部份或全部的資料複製到某 Byte 陣列中
    fs.Read(mBinaryAry, 0, CInt(fs.Length))

    '根據 Byte 陣列建立 MemoryStream 物件
    Dim bf As New IO.MemoryStream(mBinaryAry)
    bf.Position = 0
    myImg = Image.FromStream(bf)
    Me.BackgroundImage = myImg

Catch ex As Exception
    MessageBox.Show(ex.Message)

Finally
    If Not fs Is Nothing Then
        fs.Close()
    End If
End Try


方法二:

Dim fs As IO.FileStream
fs = New IO.FileStream(Application.StartupPath + "\myImg.jpg", IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = Image.FromStream(fs)
fs.Close()


Visual Basic 2005 中的 File.ReadAllBytes 與 My.Computer.FileSystem.ReadAllBytes 方法能夠讀取二進位檔,傳回成一個位元組陣列,並自行將二進位檔關閉。

方法三:

Dim myImg As Image
Try
    '用 My.Computer.FileSystem.ReadAllBytes 方法讀取二進位檔並傳回到一 Byte 陣列中
    Dim mBinaryAry As Byte() = My.Computer.FileSystem.ReadAllBytes(Application.StartupPath + "\myImg.jpg")

    '根據 Byte 陣列建立 MemoryStream 物件
    Dim bf As New IO.MemoryStream(mBinaryAry)
    PictureBox1.Image = Image.FromStream(buffer)
    Me.BackgroundImage = myImage

Catch ex As Exception
    MessageBox.Show(ex.Message)

End Try


方法四:

Dim myImg As Image
Try
    '用 My.Computer.FileSystem.ReadAllBytes 方法讀取二進位檔並傳回到一 Byte 陣列中
    Dim mBinaryAry As Byte() = File.ReadAllBytes(Application.StartupPath + "\myImg.jpg")

    '根據 Byte 陣列建立 MemoryStream 物件
    Dim bf As New IO.MemoryStream(mBinaryAry)
    PictureBox1.Image = Image.FromStream(buffer)
    Me.BackgroundImage = myImage

Catch ex As Exception
    MessageBox.Show(ex.Message)

End Try



FileStream 物件
    1. 方法
名稱說明 
Read 從資料流讀取位元組區塊(可指定數目),並將資料寫入指定緩衝區(Byte 陣列)。
ReadByte 從檔案讀取一個位元組(傳回成一個整數),並將讀取位置前移一個位元組。

    2. 屬性
名稱說明 
Length取得資料流的位元組長度。 
Position取得或設定這個資料流的目前位置。


參考:.NET Framework 類別庫 - FileStream 成員
arrow
arrow
    全站熱搜

    tsuozoe 發表在 痞客邦 留言(0) 人氣()