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.
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:
nice, here is the full info of python base64: http://base64decode.net/python-base64-b64decode
ReplyDeleteCool! your solution looks easier than mine, thanks.
DeleteI'm not a developer, i always use the free online base64 image converter to encode and decode base64 image.
ReplyDeleteOhh nice!! Thanks for sharing :D
Delete