Search...

Thursday, May 16, 2013

Base64 image Encode & Decode

Download

Step 1: Create new protect of type Windows Forms Application and design the form as given below.



Note: Use PictureBox control to display image.
Step 2: Update the Form1.cs as follows.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

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

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            // image filters
            fileDialog.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                // display image in picture box
                pictureBox1.Image = new Bitmap(fileDialog.FileName);
            }
        }

        private void btnEncode_Click(object sender, EventArgs e)
        {
            textBox1.Text = ImageToBase64(pictureBox1.Image, ImageFormat.Jpeg);
            pictureBox1.Image = null;
        }

        private void btnDecode_Click(object sender, EventArgs e)
        {
         
            pictureBox1.Image = Base64ToImage(textBox1.Text);
        }

        public string ImageToBase64(Image image,ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

        public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }
    }
}



No comments: