首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

2012-03-04 
修改一个图片的大小我想修改某一目录下的图片的大小.我用如下方法:privatevoidbutton1_Click(objectsender

修改一个图片的大小
我想修改某一目录下的图片的大小.
我用如下方法:
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;
}
}

热点排行