[C#][VB.NET]將圖片檔案存於記憶體中,並且讀出到 PictureBox 中

  • 37593
  • 0
  • 2010-08-02

將圖片檔案存於記憶體中,並且讀出到 PictureBox 中

1. 問題描述

如何將圖片檔案存於記憶體中,並且讀出到 PictureBox 中

2. 方法

使用 MemoryStream 類別 : 建立支援的存放區為記憶體的資料流。MemoryStream 會將已儲存的資料封裝成不帶正負號的位元組陣列,並於建立 MemoryStream 物件之初進行初始化,或是建立一個空的陣列。可直接在記憶體中存取已封裝的資料。記憶體資料流可以減少應用程式中所需的暫存緩衝區和檔案。請參考以下程式碼與註解。

C#


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 實例化 OpenFileDialog
            OpenFileDialog op = new OpenFileDialog();
            // 設定檔案的類型
            op.Filter = "JPG|*.jpg|GIF|*.gif";
            // 使用者選擇圖片,使用者選擇正確圖片路徑時
            if (op.ShowDialog() == DialogResult.OK)
            {
                // 實例化 FileStream
                FileStream fs = new FileStream(op.FileName, FileMode.Open);
                Byte[] data = new Byte[fs.Length];
                // 把檔案讀取到位元組陣列
                fs.Read(data, 0, data.Length);
                fs.Close();
                // 實例化一個記憶體資料流 MemoryStream,將位元組陣列放入
                MemoryStream ms = new MemoryStream(data);
                // 將記憶體資料流的資料顯示於 PictureBox 中
                this.PictureBox1.Image = Image.FromStream(ms);
                ms.Dispose();
            }
        }
    }
}

VB.NET

 


Imports System.IO
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' 實例化 OpenFileDialog
        Dim op As New OpenFileDialog()
        ' 設定檔案的類型
        op.Filter = "JPG|*.jpg|GIF|*.gif"
        ' 使用者選擇圖片,使用者選擇正確圖片路徑時
        If op.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ' 實例化 FileStream
            Dim fs As New FileStream(op.FileName, FileMode.Open)
            Dim Data(fs.Length) As Byte
            ' 把檔案讀取到位元組陣列
            fs.Read(Data, 0, fs.Length)
            fs.Close()
            ' 實例化一個記憶體資料流 MemoryStream,將位元組陣列放入
            Dim ms = New MemoryStream(Data)
            ' 將記憶體資料流的資料顯示於 PictureBox 中
            Me.PictureBox1.Image = Image.FromStream(ms)
            ms.Dispose()
        End If
    End Sub
End Class

 

3. 參考

[VB.NET][C#.NET] MemoryStream / BufferedStream 類別