Blog Stats
  • Posts - 152
  • Articles - 0
  • Comments - 36
  • Trackbacks - 0

 

Image Rotate, in ASP.Net

So continuing work on the moving map GPSd application (yes, I’m still banging on about this).

Previously, I was limited to displaying my ship/plane icon at fixed 45 degree angles,  i.e North, North-East, West etc.     Although this works really nicely,  its not quite as nice as being able to display an image at an arbitrary angle.   So I guess I could have 360 different pictures,  but what I really needed was a nice way to display a pushpin on the Virtual Earth map at any angle.

    image 

Furthermore,   I needed to preserve transparency  so that icon didn’t obscure the background.   Reading around the web,  this seems to be something that lots of people have tried to-do, so I thought I would post the source of my asp.net image rotate code.

Here’s how to use it fist of all in HTML. 

<img src=”imagerotate.asp?angle=34&image=ourpath/ourimage.png”>

Here, is the full source of imagerotate.aspx   (obviously there is nothing in the page body, just this code behind).   Please note that the transparency colour is set to WHITE, but change as you require.

 

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
 
public partial class ImageDisplay : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int angle = 0;
        string image = "";
        try
        {
            angle = Convert.ToInt32(Request["angle"].ToString());
            image = Request["image"].ToString();
        }
        catch
        {
            return;
        }
 
        string imagepath = Server.MapPath(image);
        Bitmap b = new Bitmap(imagepath);
 
        Bitmap rotated = rotateImage(b, angle);
       
        using (MemoryStream stream = new MemoryStream())
        {
            rotated.MakeTransparent(Color.White);
            rotated.Save(stream, ImageFormat.Png);
 
            Response.Clear();
            Response.ContentType = "image/png";
            stream.WriteTo(Response.OutputStream);
        }
        b.Dispose();
        rotated.Dispose();
    }
 
    private Bitmap rotateImage(Bitmap b, float angle)
    {      
        Bitmap returnBitmap = new Bitmap(b.Width, b.Height,PixelFormat.Format32bppPArgb);
        Graphics g = Graphics.FromImage(returnBitmap);
        g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
        g.RotateTransform(angle);
        g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
        g.DrawImage(b, new Point(0, 0));
        return returnBitmap;
    }
}

 

Technorati Tags:

Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

 

 

Copyright © Richard Jones