다음을 통해 공유


C#: Download an Image and Convert it to Text (Base 64)

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 useful: just because you can use MIME objects as free text, which will allow you to send it for a much more wide of applications and systems. And of course because it uses 6bit data objects instead of 8bit data.

But because I want to show you a useful scenario we might consider one in which 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 conversion 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:

01 WebRequest req = WebRequest.Create("http://yourimageURL.com");
02 WebResponse response = req.GetResponse();
03 Stream stream = response.GetResponseStream();
04 Image img = Image.FromStream(stream);
05 string result;
06 using (MemoryStream mstr = new MemoryStream())
07  {
08  img.Save(mstr, img.RawFormat);
09  result = Convert.ToBase64String(mstr.ToArray());
10  }
11 return result;