Windows phone7.1中PNG图片转base64 [英] Conversion of PNG image to base64 in Windows phone7.1

查看:21
本文介绍了Windows phone7.1中PNG图片转base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将路径中找到的PNG图片转换为Windows phone7.1中的html页面的base64.怎么做?

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

推荐答案

它是 PNG 图像这一事实实际上无关紧要 - 您只需要知道您有一些 字节需要转换成base64.

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.

将流中的数据读入字节数组,然后使用Convert.ToBase64String.从流中读取字节数组可能有点繁琐,具体取决于流是否通告其长度.如果是这样,您可以使用:

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

如果没有,最简单的方法可能是将其复制到 MemoryStream:

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

因此,一旦您使用 这些代码位(或任何其他合适的东西)来获取字节数组,只需使用 Convert.ToBase64String 即可离开.

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.

可能有流解决方案可以避免将整个字节数组保存在内存中 - 例如构建 base64 数据的 StringBuilder - 但它们会更复杂.除非您要处理非常大的文件,否则我会坚持上述做法.

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.

这篇关于Windows phone7.1中PNG图片转base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆