【问题标题】:C# Convert Image To FileStreamC# 将图像转换为文件流
【发布时间】:2013-02-20 20:34:55
【问题描述】:

到目前为止,我的应用程序允许用户通过文件选择器选择图像并通过 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 上传图像? 提前致谢。

【问题讨论】:

标签: c#


【解决方案1】:

要将图像写入文件流,我建议使用 Image 类的 Save 功能。即

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

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

【讨论】:

  • 如果这是一个愚蠢的问题,请道歉。当我执行应用程序时,“image.save”行出现以下错误:“值不能为空。参数名称:流”
  • @user1662290 它只是说你给了 image.Save 函数一个空值作为流参数。换句话说,ftpStream 为空!您需要确保您事先所做的操作不会导致 ftpStream 变为空。如果您需要更多帮助,请发布更多代码。
  • 嗨。感谢您的答复。比已有的工作得更好。我的错误是我正在写入 FileStream 而不是 FTPStream。 :/哎呀现在工作得很好! :D
【解决方案2】:

您可以使用Image.FromStream Method

类似这样的:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2012-08-13
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多