读书人

修改一个图片的大小解决方案

发布时间: 2012-03-04 11:13:33 作者: rapoo

修改一个图片的大小
我想修改某一目录下的图片的大小.
我用如下方法:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
if (opd.ShowDialog() == DialogResult.OK)
{
System.Drawing.Bitmap objPic, objNewPic;
try
{
objPic = new Bitmap(Image.FromFile(opd.FileName));
objNewPic = new System.Drawing.Bitmap(objPic, 80, 80);
objNewPic.Save(opd.FileName);

}
catch (Exception exp) { throw exp; }
finally
{
objPic = null;
objNewPic = null;
}
}
}
程序总是报错,可能是因为文件正在使用过程中,请问各位我该如何写?

[解决办法]



private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();
if (opd.ShowDialog() == DialogResult.OK)
{
System.Drawing.Bitmap objPic, objNewPic;
try
{
objPic = new Bitmap(Image.FromFile(opd.FileName));
objNewPic = new System.Drawing.Bitmap(objPic, 80, 80);
objNewPic.Save(opd.FileName+ ".tmp ");

}
catch (Exception exp) { throw exp; }
finally
{
objPic.Dispose();


objNewPic.Dispose();
if File.Exists(opd.FileName)
{
File.Delete(opd.FileName);
File.Move(opd.FileName+ ".tmp ", opd.FileName);
}
}
}
}

[解决办法]
//看来是文件被占用导致,参考如下代码解决:

OpenFileDialog opd = new OpenFileDialog();
if (opd.ShowDialog() == DialogResult.OK)
{
System.Drawing.Bitmap objPic, objNewPic;
try
{
Image objImg = Image.FromFile(opd.FileName); // < < < < < < < //这里占用了文件
objPic = new Bitmap(objImg);
objNewPic = new System.Drawing.Bitmap(objPic, 80, 80);
objImg.Dispose(); // < < < < < < < //这里释放文件
objNewPic.Save(opd.FileName);
}
catch (Exception exp) { throw exp; }
finally
{
objPic = null;
objNewPic = null;
}
}

读书人网 >C#

热点推荐