gpt4 book ai didi

c# - 使用StreamReader复制图像时损坏

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:47 24 4
gpt4 key购买 nike

是代码中的问题。
我正在尝试读取.gif文件并写入另一个.gif文件,如果我这样做...新创建的.gif文件将不会显示正确的图像,插入的垃圾图像是代码错误。

 private void ReadFile()
{
StreamReader MyReader = new StreamReader(@"C:\\Users\\admin\\Desktop\\apache_pb22_ani.gif");
string ReadFile= MyReader.ReadToEnd();
MyReader .Close ();

StreamWriter MYWriter = new StreamWriter(@"C:\\Hi.gif");
MYWriter.Write(ReadFile);
MYWriter.Close();

//throw new NotImplementedException();
}


如果我从服务器读取图像并且如果我写入图像文件,也会出现相同的问题,那是什么问题...
从服务器读取图像并写入的代码在这里

StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://10.10.21.178/Untitled.jpg");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();

string tempString = null;
int count = 0;

StreamWriter FileWriter = new StreamWriter("C:\\Testing.jpg");


do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text.
// Not needed if you'll get binary content.

tempString = Encoding.ASCII.GetString(buf, 0, count);
FileWriter.Write(tempString);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?

FileWriter.Close();

// print out page source
// Console.WriteLine(sb.ToString());
//throw new NotImplementedException();
}

最佳答案

二进制数据(例如图像)在.NET字符串中不起作用;您想要类似的东西(假设没有File.Copy选项):

using(Stream source = File.OpenRead(fromPath))
using(Stream dest = File.Create(toPath)) {
byte[] buffer = new byte[1024];
int bytes;
while((bytes = source.Read(buffer, 0, buffer.Length)) > 0) {
dest.Write(buffer, 0, bytes);
}
}


这会将图像视为二进制( byte[]),并使用缓冲区/循环来避免在图像较大时爆炸(当 File.ReadAllBytes可能很昂贵时)。

关于c# - 使用StreamReader复制图像时损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1635283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com