venerdì 10 maggio 2013

Trasformazione immagini in Base64 (C#)

La trasformazione Base64 non fa altro che trasformare un immagine in una stringa che può essere facilmente memorizzato in un Database. Di seguito una piccola funzione in C# che a partire dal Path del file restituisce una stringa contenente l'immagine codificata: 

Code:
        private string GenerateBase64(string PathFile)
        {
            string StrBase64 = null;

            System.IOFileStream inFile;
            byte[] binaryData;

            try
            {
                inFile = new System.IOFileStream(PathFile,
                                          System.IO.FileMode.Open,
                                          System.IO.FileAccess.Read);
                binaryData = new Byte[inFile.Length];
                long bytesRead = inFile.Read(binaryData, 0,
                                     (int)inFile.Length);
                inFile.Close();
            }
            catch (SystemException exp)
            {
                throw new Exception(exp.Message);
            }

            // Convert the binary input into Base64 UUEncoded output.
            try
            {
                StrBase64 =
                  System.Convert.ToBase64String(binaryData,
                                         0,
                                         binaryData.Length);
            }
            catch (SystemException exp)
            {
                throw new Exception(exp.Message);
            }

            return(StrBase64);  
        }