Tuesday, January 25, 2011

Convert Image to base64 string and base64 to image..

 private void btnBase64_Click(object sender, EventArgs e)
        {
            // Open the image file for reading.
            FileStream fs = File.OpenRead("test.gif");

            // Get the bytes for the image
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);

            // Convert the bytes into a base64 string.
            string base64 = Convert.ToBase64String(data);

            // Display the string into the textbox. 
            textBox1.Text = base64;

            // Use the string in the textbox to convert back into bytes.
            byte[] byteImage = Convert.FromBase64String(base64);

            // Create a memorystream using the bytes
            MemoryStream m = new MemoryStream(byteImage);

            //Create a bitmap image using the memorystream.
            Bitmap img = new Bitmap(m);

            // Change the forms background image to the bitmap image.
            this.BackgroundImage = img;
        }

No comments:

Post a Comment