Download an Image and Convert it to Text (Base 64) [en-US]

While developing applications we might need to send images between systems or even between classes of our own application. To do this kind of task you might use the object Image or as i propose, use the base64 format of your images.

This base64 object is a group of similar encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

Why is it usefull: Just because you can use MIME objects as free text, wich will allow you to send it for a much more wide of applicattions and systems. And of course because it uses 6bit data objects instead of 8bit data.

But because i want to show you a usefull scenario we might consider one in wich we download an image from a website, convert it to base64 and send it as an email to someone. You do this because maybe your client only support 6bit data, and because your image is 8 bit data, the base64 convertion will transform you image in a 6bit data based object.

The algorithm to download the image and convert it to base64 is for example the following:

WebRequest req = WebRequest.Create("http://yourimageURL.com");
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream);
string result;
using (MemoryStream mstr = new MemoryStream())
 {
 img.Save(mstr, img.RawFormat);
 result = Convert.ToBase64String(mstr.ToArray());
 }
return result;

Just a few lines of code,

Thats it,

Thank you,

Rui Machado

Anúncios

Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s