Craig
Craig

Reputation: 18724

Rotating an image - readonly

I found code to rotate an image. My problem is that when I save it, the image is already opened, and in use by me (As, I opened it to rotate it).

How can I avoid this?

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

        }

edit: Updated code as per Anthony's advice.

edit:

Just some FYI, this was accomplished in a couple of lines...

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

        }

    }

Upvotes: 1

Views: 2491

Answers (1)

Robert Beaubien
Robert Beaubien

Reputation: 3156

Using your existing code you can do the following:

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

That will not have the file locked when you go to save it.

Upvotes: 2

Related Questions