2011-12-29 8 views
0

画像を回転させるコードが見つかりました。私の問題は、私がそれを保存すると、イメージが既に開かれていることと、私が使用している(As、私はそれを回転させるために開いた)ということです。画像を回転する - 読み取り専用

どうすればこの問題を回避できますか?

 public static void RotateImage(string filePath, float angle) 
    { 
     //create a new empty bitmap to hold rotated image 

     using (var img = Image.FromFile(filePath)) 
     { 

      using(var bmp = new Bitmap(img.Width, img.Height)) 
      { 

       //turn the Bitmap into a Graphics object 
       Graphics gfx = Graphics.FromImage(bmp); 

       //now we set the rotation point to the center of our image 
       gfx.TranslateTransform((float) bmp.Width/2, (float) bmp.Height/2); 

       //now rotate the image 
       gfx.RotateTransform(angle); 

       gfx.TranslateTransform(-(float) bmp.Width/2, -(float) bmp.Height/2); 

       //set the InterpolationMode to HighQualityBicubic so to ensure a high 
       //quality image once it is transformed to the specified size 
       gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; 

       //now draw our new image onto the graphics object 
       gfx.DrawImage(img, new Point(0, 0)); 

       //dispose of our Graphics object 
      } 
      img.Save(filePath); 

     } 

編集:Anthonyの助言によるコードが更新されました。

編集:

は、単にいくつかのFYI、これは

public static void RotateImage(string filePath, float angle) 
    { 
     //create a new empty bitmap to hold rotated image 
     byte[] byt = System.IO.File.ReadAllBytes(filePath); 
     var ms = new System.IO.MemoryStream(byt); 

     using (Image img = Image.FromStream(ms)) 
     { 
      RotateFlipType r = angle == 90 ? RotateFlipType.Rotate90FlipNone : RotateFlipType.Rotate270FlipNone; 
      img.RotateFlip(r); 
      img.Save(filePath); 

     } 

    } 
+0

一時的な名前に保存してから、以前のファイルをすべて上書きしても上書きできませんか?このトピックでは、使い捨てオブジェクトを 'using(var obj = new DisposableObject()) 'で囲む必要があります。 –

+0

ありがとうございましたAnthony - 私はもっとクリーンな方法があると思っていました。おそらく何とかメモリストリームに保存し、ストリームを同じファイルに保存しますか? (そして、ありがとう - 私は使用して、質問を更新して実装しました) – Craig

答えて

2

では、次の操作を行うことができ、既存のコードを使用して...数行で達成された:

  byte[] byt = System.IO.File.ReadAllBytes(filepath); 
    System.IO.MemoryStream ms = new System.IO.MemoryStream(byt); 
    Image img = Image.FromStream(ms); 

保存するときにファイルがロックされません。

+0

ありがとう!ロックの問題はありませんが、私のイメージは変わりませんでした。どこかにバグがあるはずです。 – Craig

関連する問題