c# - 参数异常 "parameter is incorrect"

标签 c#

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

此外,如何将 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);
            }
        }
    }
}

最佳答案

我怀疑问题出在您如何阅读此处的文件:

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 指令,因为目前你让它保持打开状态。

关于c# - 参数异常 "parameter is incorrect",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265394/

相关文章:

c# - 在自定义 UserControl 上强制使用透明背景

c# - 复制文件网络驱动器获得大约 260 个字符限制 C#

c# - 跨线程操作无效(How to access WinForm elements from another module events?)

c# - 如何使用 FirstOrDefault 避免 Object reference not set to instance of object 错误?

c# - 如何从外部系统在 Sitecore 中添加目标/事件/结果?

c# - 页面生命周期 - 使用 FindControl 引用在页面加载期间以编程方式创建的控件

c# - 带有运算符的泛型 C#

c# - 捕获特定的 MySQL 错误 (C#)

c# - 比较项目列表然后拆分

c# - 如何检查某人是否连接到 Access DB