Conversion of PNG image to base64 in Windows phone7.1

白昼怎懂夜的黑 提交于 2019-12-13 08:26:03

问题


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;
        }

回答1:


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:

byte[] data = new byte[(int) stream.Length];
int offset = 0;
while (offset < data.Length)
{
    int bytesRead = stream.Read(data, offset, data.Length - offset);
    if (bytesRead <= 0)
    {
        throw new EndOfStreamException("Stream wasn't as long as it claimed");
    }
    offset += bytesRead;
}

If it doesn't, the simplest approach is probably to copy it to a MemoryStream:

using (MemoryStream ms = new MemoryStream())
{
    byte[] buffer = new byte[8 * 1024];
    int bytesRead;
    while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        ms.Write(buffer, 0, bytesRead);
    }
    return ms.ToByteArray();
}

So once you've used either of those bits of code (or anything else suitable) to get a byte array, just use Convert.ToBase64String and you're away.

There are probably streaming solutions which will avoid ever having the whole byte array in memory - e.g. building up a StringBuilder of 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.



来源:https://stackoverflow.com/questions/14233683/conversion-of-png-image-to-base64-in-windows-phone7-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!