I want to convert a PNG image found in a path to base64 for a html page in Windows phone7.1.How can it be done?
Stream imgStream;
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.round1.png");
byte[] data = new byte[(int)imgStream.Length];
int offset = 0;
while (offset < data.Length)
{
int bytesRead = imgStream.Read(data, offset, data.Length - offset);
if (bytesRead <= 0)
{
throw new EndOfStreamException("Stream wasn't as long as it claimed");
}
offset += bytesRead;
}
The fact that it’s a PNG image is actually irrelevant – all you need to know is that you’ve got some bytes that you need to convert into base64.
Read the data from a stream into a byte array, and then use
Convert.ToBase64String. Reading a byte array from a stream can be slightly fiddly, depending on whether the stream advertises its length or not. If it does, you can use:If it doesn’t, the simplest approach is probably to copy it to a
MemoryStream:So once you’ve used either of those bits of code (or anything else suitable) to get a byte array, just use
Convert.ToBase64Stringand you’re away.There are probably streaming solutions which will avoid ever having the whole byte array in memory – e.g. building up a
StringBuilderof base64 data as it goes – but they would be more complicated. Unless you’re going to deal with very large files, I’d stick with the above.