C#将图像转换为FileStream

到目前为止,我的应用程序允许用户通过文件选择器选择图像并通过FTP上传文件流:

Stream ftpStream = request.GetRequestStream(); FileStream file = File.OpenRead(fileToUpload); length = 1024; buffer = new byte[length]; do { bytesRead = file.Read(buffer, 0, length); ftpStream.Write(buffer, 0, bytesRead); totalReadBytesCount += bytesRead; var progress = totalReadBytesCount * 100.0 / totalToUpload; backgroundWorker1.ReportProgress((int)progress); } while (bytesRead != 0); 

这很好用。 所选图像将另存为文件,然后上载。

但是,现在,我希望将其保存为“图像”,以便我可以调整它等等。因此代码将是:

  if (openFileDialog1.ShowDialog() == DialogResult.OK) { image = Image.FromFile(openFileDialog1.FileName); } 

相反:

  if (openFileDialog1.ShowDialog() == DialogResult.OK) { file = openFileDialog1.FileName; } 

我的问题是:

现在我选择的文件是一个图像文件。 如何将其转换为文件流? 如果这不能轻易完成,那么我将如何通过ftp上传图像? 提前致谢。

要将图像写入文件流,我建议使用Image类的Save函数。 IE

 image = Image.FromFile(openFileDialog1.FileName); image.Save(ftpStream, System.Drawing.Imaging.ImageFormat.Png); 

显然,您需要检查错误并可能使用不同的图像格式。

您可以使用Image.FromStream方法 。

像这样的东西:

 image = Image.FromStream(new MemoryStream(buffer)); 

要保存到FileStream,请使用以下内容:

 var stream = File.OpenWrite(openFileDialog1.FileName); image.Save(stream, ImageFormat.Jpeg);