简体   繁体   中英

C# Image rotation

What is the best way to rotate a image in asp.net

I did use matrix.rotateAt but i can't get it to work so please tell me what is the best way?

I should write out that hate to rotate a image with the image object.

Image myImage = Image.FromFile("myimage.png");
myImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

http://msdn.microsoft.com/en-us/library/system.drawing.image.rotateflip.aspx

Here is some sample code (not written by me - found some time ago here ) that worked for me, as long as you edit some details.

private Bitmap rotateImage(Bitmap b, float angle)
{
    //create a new empty bitmap to hold rotated image
    Bitmap returnBitmap = new Bitmap(b.Width, b.Height);

    //make a graphics object from the empty bitmap
    using (Graphics g = Graphics.FromImage(returnBitmap))
    {
        //move rotation point to center of image
        g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
        //rotate
        g.RotateTransform(angle);
        //move image back
        g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
        //draw passed in image onto graphics object
        g.DrawImage(b, new Point(0, 0));
    }

    return returnBitmap;
} 

Please note, that this may not work "out of the box" - there are some issues with the new bitmap. When you rotate it, it may not fit comfortably in the rectangle of the old bitmap (rectangle bounds b.Width, B.Height).

Anyway this is just to give you an idea. If you choose to do it this way, I'm sure you will be able to work out all the details. I'd post my final code, however I don't have it on me right now...

I would suggest this is the best way

    // get the full path of image url
    string path = Server.MapPath(Image1.ImageUrl) ;

    // creating image from the image url
    System.Drawing.Image i = System.Drawing.Image.FromFile(path);

    // rotate Image 90' Degree
    i.RotateFlip(RotateFlipType.Rotate90FlipXY);

    // save it to its actual path
    i.Save(path);

    // release Image File
    i.Dispose();

    // Set Image Control Attribute property to new image(but its old path)
    Image1.Attributes.Add("ImageUrl", path);

for more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM