In this example, there is the code to convert an image file into base64 string in C#.
You can to convert a PNG into base64 string format in C# by following code
I created this exmple in Windows Form Application with following components.
Add global variables in the Form1 Class
1 2 3 4 | Bitmap image; string base64Text; |
Double click btnOpen and add these codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private void btnOpen_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG" + "|All files(*.*)|*.*"; dialog.CheckFileExists = true; dialog.Multiselect = false; if(dialog.ShowDialog()==DialogResult.OK) { image = new Bitmap(dialog.FileName); pictureBox1.Image = (Image)image; byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName); base64Text = Convert.ToBase64String(imageArray); //base64Text must be global but I'll use richtext richTextBox1.Text = base64Text; } } |
Double click btnSave and add these codes:
1 2 3 4 5 6 7 8 9 10 11 | private void btnSave_Click(object sender, EventArgs e) { string path = @"D:\sample\base64.txt"; using (StreamWriter stream= File.CreateText(path)) { // stream.Write(richTextBox1.Text); stream.Write(base64Text); } } |
All Codes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace base64Example { public partial class Form1 : Form { Bitmap image; string base64Text; public Form1() { InitializeComponent(); } private void btnOpen_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Image Files(*.BMP;*.JPG;*.PNG)|*.BMP;*.JPG;*.PNG" + "|All files(*.*)|*.*"; dialog.CheckFileExists = true; dialog.Multiselect = false; if(dialog.ShowDialog()==DialogResult.OK) { image = new Bitmap(dialog.FileName); pictureBox1.Image = (Image)image; byte[] imageArray = System.IO.File.ReadAllBytes(dialog.FileName); base64Text = Convert.ToBase64String(imageArray); //base64Text must be global but I'll use richtext richTextBox1.Text = base64Text; } } private void btnSave_Click(object sender, EventArgs e) { string path = @"D:\sample\base64.txt"; using (StreamWriter stream= File.CreateText(path)) { // stream.Write(richTextBox1.Text); stream.Write(base64Text); } } } } |
Output: