我已编写此代码用于提取图像的bitplane1。但我有例外。 实际上我得到一个图像并将其转换为字节数组所以在我改变这个字节数组后,我想将这个新的字节数组转换为图像?你能给我一些建议吗?最好的祝福 (实际上我想要提取我图像的bitplane1) 有什么建议吗?
我的代码是:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace bitplane
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Image grayImage;
OpenFileDialog o = new OpenFileDialog();
o.ShowDialog();
byte[] x = File.ReadAllBytes(o.FileName);
byte maskbyte1 = 2;
int [] newpix= new int [x.Length];
for (int i = 0; i < x.Length; i++)
{
newpix[i] = x[i] & maskbyte1;
string px=newpix[i].ToString();
x[i] = Convert.ToByte(px);
}
MemoryStream ms = new MemoryStream(x);
Image myImage = Image.FromStream(ms);
myImage.Save(@"C:\Users\Public\Pictures\Sample Pictures\New folder\fgh.jpg");
}
}
}
我的例外是这一行:
Image myImage = Image.FromStream(ms);
System.ArgumentException未处理 参数无效。
答案 0 :(得分:1)
好吧,我认为你可能在这段代码中得到的第一个例外就是:
o.ShowDialog();
byte[] x = File.ReadAllBytes(o.FileName);
请注意,无论打开文件对话框发生了什么,即使byte[] x = File.ReadAllBytes(o.FileName);
的值为null
,if (o.ShowDialog() == DialogResult.OK)
{
byte[] x = File.ReadAllBytes(o.FileName);
//... and all other codes
}
也始终会执行一次。我认为你应该首先编辑你的代码,如下所示:
o
现在代码只会在public Image ConvertByteArrayToImage(byte[] bytes)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
return Image.FromStream(stream);
}
对象返回OK时执行,这意味着选择了一个文件。
第二件事是,在你的代码中有很多地方可以抛出异常,在这种情况下,使用已经存在的方法会更好更安全。这是一个调用一个方法的方法:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
namespace bitplane
{
public partial class Form1 : Form
{
public byte[] x;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (o.ShowDialog() == DialogResult.OK)
{
OpenImage(o.FileName);
SaveImage(ConvertByteArrayToImage(x), @"C:\Users\Public\Pictures\Sample Pictures\New folder\fgh.jpg");
}
}
catch
{
MessageBox.Show("error");
}
}
public void OpenImage(string path)
{
x = File.ReadAllBytes(path);
}
public void SaveImage(Image image, string path)
{
image.Save(path);
}
public Image ConvertByteArrayToImage(byte[] bytes)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes);
return Image.FromStream(stream);
}
}
此代码几乎完成了代码已包含的所有工作。
但是有些情况下这个代码也抛出异常,所以最安全的方法是将所有东西放在try-catch块中:
{{1}}
我在你的代码中插入了一些方法,所以你可以从任何地方调用它们,而不必只在一个事件中执行它,但它也做同样的事情。
希望有所帮助! :)