旋转图像 - 只读

时间:2011-12-29 05:17:20

标签: c# asp.net

我找到了旋转图像的代码。我的问题是,当我保存它时,图像已经打开,并且由我使用(因为,我打开它来旋转它)。

我该如何避免这种情况?

        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);

        }

    }

1 个答案:

答案 0 :(得分:2)

使用现有代码,您可以执行以下操作:

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

保存时不会锁定文件。