c# - ArgumentException“参数不正确”
问题描述
我正在尝试编写一个将内存流转换为 png 图像的代码,但是在using(Image img = Image.FromStream(ms))时出现ArgumentException“参数不正确”错误。它没有进一步指定它,所以我不知道为什么我会收到错误以及我应该怎么做。
另外,如何将 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;
你应该考虑如果你多次点击按钮会发生什么......我强烈建议你为你的 使用一个using
指令FileStream
,因为目前你让它保持打开状态。
推荐阅读
- mysql - 将数据作为数组连接代码点火器传递
- angular - 路由器插座的角度正确用例
- javascript - 如何在 .on 方法中提供多个事件和处理程序?
- java - Java Streams TakeUntil 100 个元素过滤/收集
- php - Laravel 5.6 ytake/laravel-couchbase 身份验证问题
- javascript - 将 fetch api 与 ramda 一起使用
- php - 如果以用户身份登录,可以进入管理页面
- c# - 如何确定给定的路径字符串是否可以代表当前环境中的驱动器?
- crystal-reports - 找不到水晶报表 2008 数据库表货币
- ios - 使用 Pushkit 创建看门狗场景违反了 iOS 规定