Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Converting Images to and from Base64Format

0.00/5 (No votes)
9 Apr 2011 1  
Using System.Convert namespace to convert between base64 and images

Tutorial - Part 1

First, I would like to welcome you to part 1 of this tutorial. My name is Charles Henington and I will be explaining how to use the System.Convert namespace to convert files to a base64 string. In the next tutorial, we will begin converting these strings to an Image. (Note: The base64 string must be that of an Image, but we will get into more detail later on.) The System.Convert namespace is a very interesting namespace, it allows us to convert many different variables. The two that we will focus on today are:

  1. Convert.ToBase64String and
  2. Convert.FromBase64String

Using Statements

The using statements that we will use today are:

using System;
using System.IO;
using Sytem.Windows.Forms;

Preparation

You will first need to start a new Windows Forms Application. Now that we have this, right click on form and select View Code. Now, you see a code that looks something like this:

using System;
using System.IO;
using Sytem.Windows.Forms;

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

Now, we will start adding our controls to our Form. First, add four buttons and change the name property of button1 to btnOpen, button2 to btnSave, button3 to btnConvert2String, and button4 to btnConvert2Byte. Now that we have this done, we can add 2 strings called mOpen and mSave, and two byte[] values called mOriginalData and mConvertedData. Now open the Designer and click once on button1, Now hold the shift key down and click the other three buttons one click, one button at a time. Now all 4 buttons should be selected, release the shift key and double click on button4. Now, our code should look like this:

using System;
using System.IO;
using Sytem.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private string mOpen, mSave;
        private byte[] mOriginalData, mConvertedData;
        public Form1()
        {
            InitializeComponent();            
        }

        private void btnConvert2Byte_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }

        private void btnConvert2String_Click(object sender, EventArgs e)
        {

        }

        private void btnOpen_Click(object sender, EventArgs e)
        {

        }        
    }
}

Writing Our Code for Converting File to base64 Format

Now that we have our using statements, strings, byte[] values and button click events in place, we can start writing our code. In the btnOpen_Click event, we will use this code:

OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.Cancel)
   return;
mOpen = ofd.FileName;

In the btnSave_Click event, we will use:

SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.Cancel)
   return;
mSave = sfd.FileName;

Now, we get to the btnConvertToString_Click and btnConvertToByte_Click events. This is where the code gets interesting because this is where all the magic happens. The click events are named respectively to the actions that they do. (NOTE: Naming items to what they do, so as to make it easier for you to later on add onto the code.) The convertToString will save a file with the base64string value of the file that we will be loading, and convertToByte will save the file from the base64string that we load. (Note: When reading a base64string, if the data does not properly align (base64 file was altered and does not properly match base64 structure), the application will throw base64 string error. The ConvertToString method looks like this:

Stream stream = File.OpenRead(mOpen);
mOriginalData = new byte[stream.Length];
stream.Read(mOriginalData, 0, mOriginalData.Length);
stream.Flush();
stream.Close();

StreamWriter sw = new StreamWriter(mSave);
sw.Write(Convert.ToBase64String(mOriginalData));
sw.Flush(); sw.Close();

and the ConvertToByte method looks like this:

StreamReader sr = new StreamReader(mOpen);
mConvertedData = Convert.FromBase64String(sr.ReadToEnd());
sr.Close();
Stream stream = File.Create(mSave);
stream.Write(mConvertedData, 0, mConvertedData.Length);
stream.Flush();
stream.Close();   

Now our code is finished and ready to convert files to their base64 string and base64 strings to a file. Our completed code looks like this:

using System;
using System.IO;
using Sytem.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private string mOpen, mSave;
        private byte[] mOriginalData, mConvertedData;
        public Form1()
        {
            InitializeComponent();            
        }

        private void btnConvert2Byte_Click(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader(mOpen);
            mConvertedData = Convert.FromBase64String(sr.ReadToEnd());
            sr.Close();
            Stream stream = File.Create(mSave);
            stream.Write(mConvertedData, 0, mConvertedData.Length);
            stream.Flush();
            stream.Close();            
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == DialogResult.Cancel)
                return;
            mSave = sfd.FileName;
        }

        private void btnConvert2String_Click(object sender, EventArgs e)
        {
            Stream stream = File.OpenRead(mOpen);
            mOriginalData = new byte[stream.Length];
            stream.Read(mOriginalData, 0, mOriginalData.Length);
            stream.Flush();
            stream.Close();

            StreamWriter sw = new StreamWriter(mSave);
            sw.Write(Convert.ToBase64String(mOriginalData));
            sw.Flush(); sw.Close();

        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.Cancel)
                return;
            mOpen = ofd.FileName;            
        }        
    }
}

History

  • 9th April, 2011: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here