c# - 编码问题?

标签 c# encoding

我想从网络上获取图片,并将其转换为字节数组。但是阅读响应有问题。我怀疑它是由编码模式引起的。

        WebRequest request = WebRequest.Create("http://www.waterfootprint.org/images/gallery/original/apple.jpg");
        request.Method = "GET";
        request.Timeout = 10000;
        using (WebResponse response = request.GetResponse())
        {
            Stream stream = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(stream, encoding);

            string responseBody = streamReader.ReadToEnd(); //always invalid characters here
            streamReader.Close();
            stream.Dispose();
            byte[] buffer = Convert.FromBase64String(responseBody); 
        }

我尝试过其他编码方式,比如UTF7、Unicode等,但都没有用。有人能告诉我为什么吗?谢谢

最佳答案

    StreamReader streamReader = new StreamReader(stream, encoding);

StreamReader是一个 TextReader,它以特定的编码从字节流中读取字符。

StreamReader is designed for character input in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamReader for reading lines of information from a standard text file.

在您的情况下,您收到原始字节 - 您需要直接使用 Stream,使用 BinaryReader 或更高级别的抽象。

        byte[] buffer = Convert.FromBase64String(responseBody); 

您获得的流不是 base64 编码的 - 它是纯图像字节流,因此只需直接分配字节,最简单的方法是使用 WebClient :

using(WebClient wc = new WebClient())
byte[] buffer = wc.DownloadData("http://www.waterfootprint.org/images/gallery/original/apple.jpg");

Base 64 encoding通常在必须将二进制数据作为 ASCII 文本(即作为 XML CData 元素或一般 SOAP 的一部分)传输时使用 - 但如果您想通过 HTTP 传输二进制文件(即图像)则不使用。

关于c# - 编码问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400315/

相关文章:

c# - C# 和 .NET 3.5 中的图像大小调整效率

ruby - 如何在erb模板中使用utf-8编码的数据

python - 在 python 中编码 CSV 列表

python - 从 cmd.exe 运行时 Python 标准输出中的 Unicode 输出

java - 在导出的 JAR 中进行编码

c# - 将 Json.Net JValue 转换为 int

c# - Exchange Web 服务 API 和 401 未授权异常

c# - 在 WPF 中添加 TreeView 并在子项中使用上下文菜单

c# - EnableViewState = false - - 但好像还是 "working"

r - write.xlsx (openxlsx) 的编码问题