Click here to Skip to main content
15,880,543 members
Articles / Desktop Programming / Windows Forms

Converting Images to and from Base64Format

Rate me:
Please Sign up or sign in to vote.
4.11/5 (7 votes)
9 Apr 2011CPOL2 min read 32K   18   13
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:

C#
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:

C#
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:

C#
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:

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

In the btnSave_Click event, we will use:

C#
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:

C#
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:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
GeneralThis is great! Pin
jphitch8-Aug-14 4:28
jphitch8-Aug-14 4:28 
GeneralMessage Closed Pin
28-Dec-21 1:43
AmazonRankPro 10128-Dec-21 1:43 
GeneralTerminoligy Pin
Richard Deeming15-Apr-11 9:49
mveRichard Deeming15-Apr-11 9:49 
GeneralMy vote of 5 Pin
nodar14-Apr-11 15:56
nodar14-Apr-11 15:56 
Being agree with critical comments I still believe that this is a good article. So, Charles, we are waiting for Part II Smile | :)
GeneralRe: My vote of 5 Pin
charles henington22-Apr-11 5:25
charles henington22-Apr-11 5:25 
GeneralMy vote of 2 Pin
Kelvin Armstrong11-Apr-11 22:21
Kelvin Armstrong11-Apr-11 22:21 
GeneralRe: My vote of 2 Pin
charles henington22-Apr-11 5:28
charles henington22-Apr-11 5:28 
GeneralMy vote of 2 Pin
Michael B. Hansen11-Apr-11 1:01
Michael B. Hansen11-Apr-11 1:01 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 3:23
charles henington11-Apr-11 3:23 
GeneralRe: My vote of 2 Pin
Michael B. Hansen11-Apr-11 4:00
Michael B. Hansen11-Apr-11 4:00 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 4:04
charles henington11-Apr-11 4:04 
GeneralRe: My vote of 2 Pin
Michael B. Hansen11-Apr-11 4:18
Michael B. Hansen11-Apr-11 4:18 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 4:34
charles henington11-Apr-11 4:34 
GeneralRe: My vote of 2 [modified] Pin
Paw Jershauge12-Apr-11 1:39
Paw Jershauge12-Apr-11 1:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.