编码问题?
我想从网络上获取一张图片,并将其转换为字节数组。但阅读回复时发现有问题。我怀疑这是由编码模式引起的。
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等,但都是徒劳。有人能告诉我为什么吗?谢谢
I want to get a picture from web, and turn that into a byte array. But there is something wrong reading the response. I suspect it caused by encoding modes.
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);
}
I have tried other encoding ways, such as UTF7, Unicode, etc, but all in vain. Could someone tell me why? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
StreamReader
是一个 < em>TextReader 以特定编码从字节流中读取字符。在您的情况下,您收到原始字节 - 您需要直接使用
Stream
、使用BinaryReader
或更高级别的抽象。您获得的流不是 base64 编码的 - 它是纯图像字节流,因此只需直接分配字节,最简单的方法是使用
WebClient
:StreamReader
is a TextReader that reads characters from a byte stream in a particular encoding.In your case you receive raw bytes - You either need to work with the
Stream
directly, use aBinaryReader
or a higher level abstraction.The stream you are getting is not base64 encoded - it's a pure image byte stream, so just assign the bytes directly, easiest would be with a
WebClient
:Base 64 encoding is usually used when you must transmit binary data as ASCII text (i.e. as part of an XML CData element or SOAP in general) - but not if you want to transmit a binary file (i.e. an image) over HTTP.
它以二进制形式返回,而不是 base-64 编码。例如,如果我更改代码以直接从响应流创建图像,我会看到它出现在 PictureBox 控件中。
It comes back as binary, not base-64 encoded. For example, if I change your code to create an image directly from the response stream, I see it appear in a PictureBox control.