1. 程式人生 > >C# 將圖片轉換成base64 資料

C# 將圖片轉換成base64 資料

 //將圖片轉換成base64 資料
            FileStream fs = File.OpenRead("C:\\20180822\\161940.jpg"); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //獲得檔案長度 
            Byte[] image = new Byte[filelength]; //建立一個位元組陣列 
            fs.Read(image, 0, filelength); //按位元組流讀取 
            //System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            string imgData64 = Convert.ToBase64String(image);

/// <summary>

/// 將圖片資料轉換為Base64字串

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void ToBase64(object sender, EventArgs e)

{

Image img = this.pictureBox.Image;

BinaryFormatter binFormatter = new BinaryFormatter();

MemoryStream memStream = new MemoryStream();

binFormatter.Serialize(memStream, img);

byte[] bytes = memStream.GetBuffer();

string base64 = Convert.ToBase64String(bytes);

this.richTextBox.Text = base64;

}

/// <summary>

/// 將Base64字串轉換為圖片

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void ToImage(object sender, EventArgs e)

{

string base64 = this.richTextBox.Text;

byte[] bytes = Convert.FromBase64String(base64);

MemoryStream memStream = new MemoryStream(bytes);

BinaryFormatter binFormatter = new BinaryFormatter();

Image img = (Image)binFormatter.Deserialize(memStream);

this.pictureBox.Image = img;

}