Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Thursday, January 3, 2013

Encode an Image into base64 string in C# / Python

From previous post is about display an embed string image into HTML. So, this post is about how to get base64 string image both Python and C#.

I will start from Python which we can convert into base64 string easily using encode function.
filename = 'xxx.jpg'
f = open(filename, 'rb')
encode = f.read().encode('base64')
print encode
If you want to decode it back into original string and write it into an image file, we can do as follows:
from base64 import decodestring

decode = decodestring(encode)
print decode

output = open('temp.png', 'wb')
output.write(decode)
output.close()
From the example, the result is it will convert a jpeg image into a png image. Use "decodestring" function that imported from "base64" module.

In C# (WPF, SL, WP), we can convert it by getting resource stream then copy to memory stream array, and convert it into base64 string.
public void Convert()
{
     string filename = "xxx.jpg";
     StreamResourceInfo sri = null;
     Uri uri = new Uri(fileName, UriKind.Relative);
     sri = Application.GetResourceStream(uri);

     using (var memoryStream = new MemoryStream())
     {
          sri.Stream.CopyTo(memoryStream);
          byte[] result = memoryStream.ToArray();
          string base64 = System.Convert.ToBase64String(result);
     }
}
For both Python and C# from my code, if you want to send the data upload to the web server using HTTP POST method, you need to do another step by encoding into the same form format in the sever side such as url-encode. You can take a look in my old posts to send data using HTTP POST for Python and C#.

References:

4 comments:

  1. nice, here is the full info of python base64: http://base64decode.net/python-base64-b64decode

    ReplyDelete
    Replies
    1. Cool! your solution looks easier than mine, thanks.

      Delete