Bitmap处理完最后一张图片时,出现了ms(变量)参数无效,代码如下:
private void button4_Click(object sender, EventArgs e)
{
if ((textBox1.Text == null) || (textBox2.Text == null) || (or == null) || (pu == null)) {
MessageBox.Show("请完善信息!");
}
else
{
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
string d1;
string d2;
List<string> na = new List<string>();
DirectoryInfo d = new DirectoryInfo(or);
FileInfo[] file = d.GetFiles();
foreach (FileInfo f in file)
{
na.Add(f.Name);
}
foreach(string filename in na) {
i = 1;
a = 1;
FileInfo fpic = new FileInfo(or + @"\" + filename);
FileStream fs = new FileStream(or + @"\" + filename, FileMode.Open);
byte[] byDate = new byte[fs.Length];
fs.Read(byDate, 0, byDate.Length);
fs.Close();
MemoryStream ms = new MemoryStream(byDate);
Bitmap pic = new Bitmap(ms);
wi = pic.Width;
he = pic.Height;
listBox1.Items.Add(filename + "尺寸:" + wi.ToString() + "×" + he.ToString());
listBox1.TopIndex = listBox1.Items.Count - (int)(listBox1.Height / listBox1.ItemHeight);
do
{
if ((wi > (i - 1) * longth) && (wi <= i * longth))
{
d1 = ((i - 1) * longth).ToString() + "≤宽≤" + (i * longth).ToString();
if (!Directory.Exists(pu + @"\" + d1)) {
Directory.CreateDirectory(pu + @"\" + d1);
}
do
{
if ((he > (a - 1) * wideth) && (he <= a * wideth))
{
d2 = ((a - 1) * wideth).ToString() + "≤高≤" + (a * wideth).ToString();
if (!Directory.Exists(pu + @"\" + d1 + @"\" + d2))
{
Directory.CreateDirectory(pu + @"\" + d1 + @"\" + d2);
}
fpic.CopyTo(pu + @"\" + d1 + @"\" + d2 + @"\" + filename, true);
ln = false;
} else
{
ln = true;
a++;
}
} while (ln);
en = false;
}
else
{
en = true;
i++;
}
} while (en);
pic.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
}
listBox1.Items.Add("完成!");
listBox1.TopIndex = listBox1.Items.Count - (int)(listBox1.Height / listBox1.ItemHeight);
textBox1.ReadOnly = false;
textBox2.ReadOnly = false;
textBox3.ReadOnly = false;
textBox4.ReadOnly = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
}
}
异常如下:
问一下这怎么解决?
你为啥要通过流转来转去的,直接写bitmap.fromfile不就行了
此外,你在遍历文件夹,你确定文件夹里全是图片,没有乱七八糟别的东西吗,先判断类型再加入na,不要把非图片文件加入na
那就把发生异常的文件路径打印出来,然后单独个测试代码测试这个文件不在循环里能用bitmap读么
毕竟bitmap本身就读不出来的文件,你再咋弄都是浪费时间。