Translate

Monday, July 6, 2015

Base64 Encoder

private void button1_Click(object sender, EventArgs e)
{
   this.openFileDialog1.InitialDirectory = GetDownloadsPath();
   if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
   {
       try
       {
           textBox2.Text = "";
           Cursor.Current = Cursors.AppStarting;
           toolStripStatusLabel1.Text = "Working ...";
           string path = openFileDialog1.FileName;
           string fileExt = Path.GetExtension(path).ToLower().Replace(".", String.Empty);
           textBox1.Text = path;
           textBox1.Refresh();
           _image = Image.FromFile(this.textBox1.Text);

           var imgHeight = _image.Height;
           var imgWidth = _image.Width;
           pictureBox1.Height = imgHeight;
           pictureBox1.Width = imgWidth;
           pictureBox1.Image = _image;
           pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
           pictureBox1.Refresh();

           using (MemoryStream ms = new MemoryStream())
           {
               _image.Save(ms, _image.RawFormat);
               byte[] buffer = ms.ToArray();
               StringBuilder sb = new StringBuilder();
               sb.Append(String.Format("data:image/{0};base64,", fileExt));
               sb.Append(Convert.ToBase64String(buffer));
               this.textBox2.Text = sb.ToString();
           }
       }
       catch (IOException ioEx)
       {
           MessageBox.Show("Error: Could not read image file from disk. Orignal error: " + ioEx.Message, "Error");
       }
       catch (Exception ex)
       {
           MessageBox.Show("Error: " + ex.Message, "Error");
       }
       finally
       {
           Cursor.Current = Cursors.Default;
           toolStripStatusLabel1.Text = "Ready";
       }
   }
}