Click here to Skip to main content
11,705,208 members (50,523 online)
Click here to Skip to main content

Converting Images to and from Base64Format

, 9 Apr 2011 CPOL 13.9K 18
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

charles henington
United States United States
I do not claim to be wrong! I just rarely ever write.

You may also be interested in...

Comments and Discussions

 
GeneralThis is great! Pin
jphitch8-Aug-14 4:28
memberjphitch8-Aug-14 4:28 
GeneralTerminoligy Pin
Richard Deeming15-Apr-11 9:49
memberRichard Deeming15-Apr-11 9:49 
GeneralMy vote of 5 Pin
nodar14-Apr-11 15:56
membernodar14-Apr-11 15:56 
GeneralRe: My vote of 5 Pin
charles henington22-Apr-11 5:25
membercharles henington22-Apr-11 5:25 
GeneralMy vote of 2 Pin
Kelvin Armstrong11-Apr-11 22:21
memberKelvin Armstrong11-Apr-11 22:21 
GeneralRe: My vote of 2 Pin
charles henington22-Apr-11 5:28
membercharles henington22-Apr-11 5:28 
GeneralMy vote of 2 Pin
Michael B. Hansen11-Apr-11 1:01
memberMichael B. Hansen11-Apr-11 1:01 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 3:23
membercharles henington11-Apr-11 3:23 
GeneralRe: My vote of 2 Pin
Michael B. Hansen11-Apr-11 4:00
memberMichael B. Hansen11-Apr-11 4:00 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 4:04
membercharles henington11-Apr-11 4:04 
GeneralRe: My vote of 2 Pin
Michael B. Hansen11-Apr-11 4:18
memberMichael B. Hansen11-Apr-11 4:18 
GeneralRe: My vote of 2 Pin
charles henington11-Apr-11 4:34
membercharles henington11-Apr-11 4:34 
GeneralRe: My vote of 2 [modified] Pin
Paw Jershauge12-Apr-11 1:39
memberPaw Jershauge12-Apr-11 1:39 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 9 Apr 2011
Article Copyright 2011 by charles henington
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid