Skip to main content
 首页 » 编程设计

C# 将图像转换为文件流

2024年02月20日9thcjp

到目前为止,我的应用程序允许用户通过文件选择器选择图像并通过 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 函数。即.E

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

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