2013-08-27 78 views
1

我有一个网站,允许用户通过上传表单在服务器上上传一些图片。当这个图片上传时,asp.net服务应该压缩那个特定的图片。压缩图像已经很好,但是我想在压缩完成后从服务器的磁盘上删除原始图像。压缩完成后立即删除图像文件。怎么样?

请花点时间看看下面我的代码:

if (fileUl.PostedFile.ContentType == "image/jpeg" || fileUl.PostedFile.ContentType == "image/png") 
{ 
    fileUl.SaveAs(fullPath); 
    System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath); 
    compressImage(destinationPath, image, 40); 
    System.IO.File.Delete(fullPath); 

} // nested if 

如果我尝试运行上面的代码我得到

System.IO.IOException:该进程无法访问文件[filepath],因为它正在被另一个进程使用。

其实我想到的是,因为我认为这是因为,服务器仍然在压缩时的下一行代码要删除图像的图像(我认为这是它)。所以我的问题是:

如何等待压缩完成,然后运行“删除”代码?

+0

您需要调用它的** Dispose方法**。 一般来说,规则是如果一个对象实现了** IDisposable **接口,那么一旦完成它就应该调用它的** Dispose **方法。这有助于避免使用非托管资源的对象的内存泄漏。做到这一点的最佳方式是将其封装在[using statement](http://msdn.microsoft.com/en-us/library/yh598w02.aspx)中。 – CodeXerox

回答

2
using (System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
{ 
    //DO compression; 
} 
System.IO.File.Delete(fullPath); 

更好地做到这一切的压缩功能:

public void DoCompression(string destination, string fullPath, int ratio) 
{ 
    using (System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
    { 
     //DO compression by defined compression ratio. 
    } 
} 

的调用函数可能看起来像:

DoCompression(destinationPath, fullPath, 40); 
DoCompression(destinationPath, fullPath, ??); 

System.IO.File.Delete(fullPath); 
+0

它的工作原理。谢谢! – rootpanthera

+0

好,它有帮助:) – Irfan

+0

我已经接受你的答案,但我刚刚得到另一个问题。你的代码正在工作,但是如果我需要压缩并创建两个(相同)图像但是使用不同的压缩。因为我想在我的应用程序中使用缩略图的一个压缩图像,而实际图像的另一个(较高质量)。那么代码将如何?你能否更新你的答案:)? – rootpanthera

2

Image.FromFile

文件保持锁定,直到Image设置。

尝试:

System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath); 
compressImage(destinationPath, image, 40); 
image.Dispose(); //Release file lock 
System.IO.File.Delete(fullPath); 

或(稍微干净,如果有异常抛出):

using(System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
{ 
    compressImage(destinationPath, image, 40); 
} 
System.IO.File.Delete(fullPath); 
0

这取决于你在compressImage在做什么。如果你使用线程来压缩图像,那么你是对的。但我认为不同。你必须Disposeimage对象。

0

几种方法

  • 使用顺序执行

    • 阻断压缩图像
    • 阻止删除图像

    正如其他建议确保你每一个阶段

  • 使用等待句柄后正确地释放资源,如ManualResetEvent

  • 实现排队生产者 - 消费者,其中生产者排队要处理的图像,并且消费者mer会将项目出列,压缩并删除原始图像。生产者和消费者可能是不同的过程。

我可能会采用第一种方法,因为它很简单。第二种方法很容易实现,但它保留了线程并降低了Web应用程序的性能。如果您的网站负载很重,第三种方法很有用。

0

将图像包装在Using statmement中以确保正确处理图像对象。

if (fileUl.PostedFile.ContentType == "image/jpeg" || fileUl.PostedFile.ContentType == "image/png") 
{ 
    fileUl.SaveAs(fullPath); 
    using(System.Drawing.Image image = System.Drawing.Image.FromFile(fullPath)) 
    { 
     compressImage(destinationPath, image, 40); 
    } 
    System.IO.File.Delete(fullPath); 
} // nested if 
相关问题