Give image rounded corner

I would just like to know if anyone can give me some advice on how to take a jpeg image and make the corners rounded at runtime using gdi+ and aspnet.

Following code will open image file from server and stream back to browser with rounded corners.

Image with rounded corner

Run sample code.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Drawing" %>
<script runat="server">

    void Page_Init(Object sender,EventArgs e) {

        string path = Server.MapPath("~/Images/flower.jpg"); 
        int roundedDia = 50;

        
            using(Image imgin = Image.FromFile(path)){
            Bitmap bitmap = new Bitmap(imgin.Width, imgin.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.Clear(Color.White);
            g.SmoothingMode = 
(System.Drawing.Drawing2D.SmoothingMode.AntiAlias); Brush brush = new System.Drawing.TextureBrush(imgin); FillRoundedRectangle(g,
new Rectangle(0, 0, imgin.Width, imgin.Height),
roundedDia, brush);

// done with drawing dispose graphics object. g.Dispose(); // Stream Image to client. Response.Clear(); Response.ContentType = "image/pjpeg";
bitmap.Save(Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
// dispose bitmap object. bitmap.Dispose(); } } public static void FillRoundedRectangle(Graphics g,
Rectangle r,int d,Brush b){

System.Drawing.Drawing2D.GraphicsPath gp
= new System.Drawing.Drawing2D.GraphicsPath();

gp.AddArc(r.X, r.Y, d, d, 180, 90);
gp.AddArc(r.X + r.Width - d, r.Y, d, d, 270, 90);
gp.AddArc(r.X + r.Width - d, r.Y + r.Height - d, d, d, 0, 90);
gp.AddArc(r.X, r.Y + r.Height - d, d, d, 90, 90);

g.FillPath(b, gp);
}
</script>
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories