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