Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

C#: Encoder les données binaires en Base64


{filelink=19655}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace Mesexemples
{
    class Base64Exemple
    {
        static void Main(string[] args)
        {
            FileStream myStream = new FileStream(@"C:\image1.jpg", FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(myStream);
            byte[] image = new byte[reader.BaseStream.Length];
            for (int i = 0; i < reader.BaseStream.Length; i++)
            {
                image[i] = reader.ReadByte();
            }
            reader.Close();
            myStream.Close();
            string bmpAsString = EncodeBytesAsBase64(image);
        }
        public static string EncodeBytesAsBase64(byte[] sourceBytes)
        {
 
            // Conversion de séquences de 3-byte en séquence de 4-byte
            long byteLength = (long)(4.0d * sourceBytes.Length / 3.0d);
            if ((byteLength % 4) != 0)
            {
 
                byteLength += 4 - (byteLength % 4);
            }
 
            char[] encodedCharArray = new char[byteLength];
            Convert.ToBase64CharArray(sourceBytes, 0, sourceBytes.Length, encodedCharArray, 0);
 
            return (new string(encodedCharArray));
        }
    }
 
 
}

No comments yet.

Leave a Comment