[英]C# Convert Image To FileStream
My application so far lets the user select an image via the file selector and upload it through a file stream via FTP: 到目前为止,我的应用程序允许用户通过文件选择器选择图像并通过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);
This works fine. 这很好用。 The selected image is saved as a file and then uploaded.
选定的图像将另存为文件,然后上载。
Now, however, I wish to save it as a 'Image' so I can resize it etc. So that the code would be: 但是,现在,我希望将其保存为“图像”,以便我可以调整它等等。因此代码将是:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
image = Image.FromFile(openFileDialog1.FileName);
}
As opposed to: 相反:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
file = openFileDialog1.FileName;
}
My question thus is: 我的问题是:
Now my selected file is a Image file. 现在我选择的文件是一个图像文件。 How do I convert it into the filestream?
如何将其转换为文件流? If this can't be done easily then how would I upload the image via ftp?
如果这不能轻易完成,那么我将如何通过ftp上传图像? Thanks in advance.
提前致谢。
To write the image to the filestream, I would recommend using the Save function of the Image class. 要将图像写入文件流,我建议使用Image类的Save函数。 IE
IE
image = Image.FromFile(openFileDialog1.FileName);
image.Save(ftpStream, System.Drawing.Imaging.ImageFormat.Png);
Obviously, you'll need to check for errors and possibly use a different image format. 显然,您需要检查错误并可能使用不同的图像格式。
You may use Image.FromStream Method . 您可以使用Image.FromStream方法 。
Something like this: 像这样的东西:
image = Image.FromStream(new MemoryStream(buffer));
To save to FileStream use something like this: 要保存到FileStream,请使用以下内容:
var stream = File.OpenWrite(openFileDialog1.FileName);
image.Save(stream, ImageFormat.Jpeg);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.