简体   繁体   中英

Create a graphic image dynamically using C#

This is a .net web site. I have a list of 100 x,y coordinates.

I need to display 100 octagonal shapes the centre point of which sits at the respective co-ordinate.

I toyed with doing this by passing an array to javascript and dynamically creating and positioning the images. But it looks awful and resizing the browser window causes problems etc.

So, can I create a graphic myself? I saw this code answering a similar question:

    using (Bitmap bmp = new Bitmap(10, 10))
    { 
        using (Graphics g = Graphics.FromImage(bmp)) 
        { 
            g.Clear(Color.White); 
            g.DrawLine(Pens.Black, new PointF(9.56f, 4.1f), 
                                           new PointF(3.456789f, 2.12345f)); 
        } 
        bmp.Save(@"c:\myimage.jpg", ImageFormat.Jpeg);
    }

Can you draw octagons easily enough using this?

However, when I try to run the code above, I am getting this error.

A generic error occurred in GDI+

I don't want to spend a long time working out out to draw octagons etc. if I can't get it to run.

One last thing, I don't need to save the graphic, I just want to display it as though it were an image I'm getting from the images folder.

Edit: Further to suggestion below I have modified the code like this:

using (MemoryStream ms = new MemoryStream())
            {
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] buffer = ms.GetBuffer();
                HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length); 
            }

This is putting my drawing on the screen. Is there anything that should be tweaked?

You probably don't have write access to C:\\ .

Instead of saving to disk, you should save to a MemoryStream , then render it to the HTTP response. (inside of an ASHX or MVC action)

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