【问题标题】:ArgumentException "parameter is incorrect"ArgumentException“参数不正确”
【发布时间】:2018-11-13 15:27:39
【问题描述】:

我正在尝试编写将内存流转换为 png 图像的代码,但在 using(Image img = Image. FromStream(ms))。它没有进一步指定它,所以我不知道为什么我会收到错误以及我应该怎么做。

另外,我如何将 Width 参数与 img.Save(filename + ".png", ImageFormat.Png); 一起使用?我知道我可以添加参数并且它识别“宽度”,但我不知道它应该如何格式化以便 Visual Studio 接受它。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MemoryStream ms = new MemoryStream();
        public string filename;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ConvertFile();
        }

        private void OpenFile()
        {
            OpenFileDialog d = new OpenFileDialog();

            if(d.ShowDialog() == DialogResult.OK)
            {
                filename = d.FileName;
                var fs = d.OpenFile();
                fs.CopyTo(ms);
            }
        }

        private void ConvertFile()
        {
            using(Image img = Image.FromStream(ms))
            {
                img.Save(filename + ".png", ImageFormat.Png);
            }
        }
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    我怀疑问题在于您在此处读取文件的方式:

    fs.CopyTo(ms);
    

    您将文件的内容复制到MemoryStream,但随后将MemoryStream 置于数据的结束而不是开始。您可以通过添加以下内容来解决此问题:

    // "Rewind" the memory stream after copying data into it, so it's ready to read.
    ms.Position = 0;
    

    您应该考虑如果您多次单击按钮会发生什么...我强烈建议您为您的FileStream 使用using 指令,因为目前您将其保持打开状态。

    【讨论】:

    • 好消息,但这并不能解决问题
    • @SusiKette:您是否尝试过完全删除 UI 方面的东西?如果您只是使用File.OpenRead 打开文件的流,然后在那里调用Image.FromStream 怎么办? 那个有用吗?文件的开头格式是什么?
    • 这是一个原始文件。这有关系吗?它仍然应该能够从文件中读取字节。我知道文件本身是图像数据,因为我已经手动/手动进行了一些转换,但是文件很大,所以转换器肯定会有所帮助。现在我只希望程序从输入数据中输出一个 png 文件,然后当我有视觉输出帮助我进行转换时添加一些东西以更接近我的目标。
    • @SusiKette:是的,这绝对重要。您要求Image 类将字节解释为作为图像 - 因此需要采用它知道的格式。如果“原始文件”是指没有标题信息等来解释格式,那将是一个问题。
    • 还有办法定义必要的信息吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2019-05-23
    • 2015-05-27
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多