旋转图像-只读

本文关键字:-只读 图像 旋转 | 更新日期: 2023-09-27 18:19:04

我找到了旋转图像的代码。我的问题是,当我保存它时,图像已经打开,并由我使用(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);
        }

edit:根据Anthony的建议更新代码。

编辑:

仅供参考,这是在几行中完成的…

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

旋转图像-只读

使用您现有的代码,您可以做以下事情:

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

当你保存文件时,它将不会被锁定