C # picture and BASE64 code conversion to each other
Last Update:2016-11-10
Source: Internet
Author: User
Picture converted to Base64 encoded text
private void Button1_Click (object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog ();
Dlg. MultiSelect = true;
Dlg. Title = "Select the picture to convert";
Dlg. Filter = "Image files (*.jpg;*.bmp;*.gif;*.png) |*.jpg*.jpeg;*.gif;*.bmp| Allfiles (* *) |*.* ";
if (DialogResult.OK = = dlg. ShowDialog ())
{
for (int i = 0; i < dlg. Filenames.length; i++)
{
Imgtobase64string (dlg. Filenames[i]. ToString ());
}
}
}
Picture converted to Base64 encoded text
private void Imgtobase64string (string imagefilename)
{
Try
{
Bitmap bmp = new Bitmap (imagefilename);
This.pictureBox1.Image = BMP;
FileStream fs = new FileStream (Imagefilename + ". txt", filemode.create);
StreamWriter SW = new StreamWriter (FS);
MemoryStream ms = new MemoryStream ();
Bmp. Save (MS, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new Byte[ms. Length];
Ms. Position = 0;
Ms. Read (arr, 0, (int) Ms. Length);
Ms. Close ();
String strbaser64 = convert.tobase64string (arr);
Sw. Write (STRBASER64);
Sw. Close ();
Fs. Close ();
MessageBox.Show ("Successful conversion!");
}
catch (Exception ex)
{
MessageBox.Show ("imgtobase64string conversion failed \nexception:" + ex. Message);
}
}
Base64 encoded text to image
private void Button2_Click (object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog ();
Dlg. MultiSelect = true;
Dlg. Title = "Select the Base64 encoded text to convert";
Dlg. Filter = "txt files|*.txt";
if (DialogResult.OK = = dlg. ShowDialog ())
{
for (int i = 0; i < dlg. Filenames.length; i++)
{
Base64stringtoimage (dlg. Filenames[i]. ToString ());
}
}
}
Base64 encoded text to image
private void Base64stringtoimage (string txtfilename)
{
Try
{
FileStream ifs = new FileStream (Txtfilename, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader (IFS);
String inputstr = Sr. ReadToEnd ();
byte[] arr = convert.frombase64string (INPUTSTR);
MemoryStream ms = new MemoryStream (arr);
Bitmap bmp = new Bitmap (MS);
Bmp. Save (Txtfilename + ". jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Bmp. Save (Txtfilename + ". bmp", imageformat.bmp);
Bmp. Save (Txtfilename + ". gif", imageformat.gif);
Bmp. Save (Txtfilename + ". png", imageformat.png);
Ms. Close ();
Sr. Close ();
Ifs. Close ();
This.pictureBox2.Image = BMP;
if (file.exists (txtfilename))
{
File.delete (Txtfilename);
}
MessageBox.Show ("Conversion succeeded!") ");
}
catch (Exception ex)
{
MessageBox.Show ("Base64stringtoimage conversion failed \nexception:" + ex. Message);
}
}