locked
FAQs:如何旋转或者翻转图片? RRS feed

答案

  • 用Image.RotateFlip方法可以旋转图片90/180/270度或者垂直/水平翻转图片。

    RotateFlip的参数是System.Drawing.RotateFlipType,该参数指定了提高给图片的旋转和翻转的类型。

    代码片段:
    //指定了无翻转的90度旋转
    pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
    //指定了无旋转的水平翻转
    pictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
    //指定了90度的旋转,然后水平翻转
    pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipXY);

    如果想要以任意角度旋转图片,可以使用System.Drawing.Drawing2D.Matrix
    代码片段:
    public static Bitmap RotateImg(Bitmap bmp, float angle, Color bkColor)
            {
                int w = bmp.Width;
                int h = bmp.Height;
                PixelFormat pf = default(PixelFormat);
                if (bkColor == Color.Transparent)
                {
                    pf = PixelFormat.Format32bppArgb;
                }
                else
                {
                    pf = bmp.PixelFormat;
                }

                Bitmap tempImg = new Bitmap(w, h, pf);
                Graphics g = Graphics.FromImage(tempImg);
                g.Clear(bkColor);
                g.DrawImageUnscaled(bmp, 1, 1);
                g.Dispose();

                GraphicsPath path = new GraphicsPath();
                path.AddRectangle(new RectangleF(0f, 0f, w, h));
                Matrix mtrx = new Matrix();
                //用System.Drawing.Drawing2D.Matrix类
                mtrx.Rotate(angle);
                RectangleF rct = path.GetBounds(mtrx);
                Bitmap newImg = new Bitmap(Convert.ToInt32(rct.Width), Convert.ToInt32(rct.Height), pf);
                g = Graphics.FromImage(newImg);
                g.Clear(bkColor);
                g.TranslateTransform(-rct.X, -rct.Y);
                g.RotateTransform(angle);
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                g.DrawImageUnscaled(tempImg, 0, 0);
                g.Dispose();
                tempImg.Dispose();
                return newImg;
            }
            public Form1()
            {
                InitializeComponent();
                pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
                pictureBox1.Image = Image.FromFile(@"C:\image.jpg");
                pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
                Bitmap bitmap = (Bitmap)pictureBox1.Image;
                pictureBox1.Image = (Image)(RotateImg(bitmap, 30.0f, Color.Transparent));
            }


    如果您对我们的论坛在线支持服务有任何的意见或建议,请通过邮件告诉我们。
    MSDN 论坛好帮手 立刻免费下载  MSDN 论坛好帮手
    2011年3月3日 5:31