c# – ArgumentException“参数不正确”
发布时间:2020-12-16 01:27:59 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个将memorystream转换为png图像的代码,但是我在使用时遇到了ArgumentException“参数不正确”错误( Image img = Image.FromStream(ms)).它没有进一步指定它,所以我不知道为什么我得到错误,我应该怎么做. 另外,如何将Width参数与img.Save(文
|
我正在尝试创建一个将memorystream转换为png图像的代码,但是我在使用时遇到了ArgumentException“参数不正确”错误(
Image img =
Image.FromStream(ms)).它没有进一步指定它,所以我不知道为什么我得到错误,我应该怎么做.
另外,如何将Width参数与img.Save(文件名“.png”,ImageFormat.Png)一起使用;?我知道我可以添加参数并识别“Width”,但我不知道它应该如何格式化,因此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指令,因为你现在要打开它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
