2016-06-21 18 views
0

これは画像のサイズを変更するためのコードです。それは正常に動作しますが、以前に作成したファイルを削除しようとすると、「ファイルは別のプロセスで使用されています」というエラーが表示されます。これはコードです:サイズ変更済み画像ファイル

try 
{ 
    int newHeight = width * fromStream.Height/fromStream.Width; 

    Image newImage = new Bitmap(width, newHeight); 
    using (Graphics graphicsHandle = Graphics.FromImage(newImage)) 
    { 
     graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic; 
     graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight); 
    } 
    string processedFileName = String.Concat(Configuration.CoverLocalPath, @"\Processed\res_", Path.GetFileName(imageFile)); 
    newImage.Save(processedFileName, ImageFormat.Jpeg); 
    newImage.Dispose(); 

    return processedFileName; 
} 
catch (Exception ex) 
{ 
    Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message); 
    return string.Empty; 
} 

私はImageオブジェクトを処分しようとしましたが、成功しませんでした。何かヒント?

+0

出力が一部のビューアで開かれている可能性があります。 –

+0

実際には、イメージがdatagridViewセル内にあります... – Ras

答えて

1

もっとコードがなければ、その難しいと言えますが、おそらく原因はあなたのfromStreamが閉じられておらず適切に処理されていないことです。私は "以前に作成された"あなたのソースストリームを意味すると仮定しています。 usingステートメントでラップしてみてください。また、例外の場合に適切に配置されるようにnewImageもラップしました。

using(var fromStream = GetSourceImageStream()) 
{ 
    try 
    { 
     int newHeight = width * fromStream.Height/fromStream.Width; 

     using(Image newImage = new Bitmap(width, newHeight)) 
     { 
     using (Graphics graphicsHandle = Graphics.FromImage(newImage)) 
     { 
      graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      graphicsHandle.DrawImage(fromStream, 0, 0, width, newHeight); 
     } 
     string processedFileName = String.Concat(Configuration.CoverLocalPath, @"\Processed\res_", Path.GetFileName(imageFile)); 
     newImage.Save(processedFileName, ImageFormat.Jpeg); 
     }  
     return processedFileName; 
    } 
    catch (Exception ex) 
    { 
     Configuration.Log.Debug("Utility.cs", "ResizeMainCover", ex.Message); 
     return string.Empty; 
    } 
    finally 
    { 
     fromStream.Close(); 
    } 
} 
関連する問題