Reputation: 2687
How can I use System.Drawing
to do this?
I just want to be able to specify dimensions and background color (in hex) and eventually end up with an Image
.
I've looked at similar questions (like this one) but they're more for WinForms - I need it for ASP.Net.
Upvotes: 1
Views: 16102
Reputation: 50728
You can use those approaches, create the image, and save it to the hard disk. Then serve it up to the user. So the extra step for ASP.NET is to save it to the hard disk. Otherwise, everything else can work as is.
Upvotes: 0
Reputation: 3734
You can't directly use System.Drawing on a ASP.NET web form, because the page is displayed by the browser, which only understands HTML and CSS, your code is executed on the server, though. For displaying a simple rectangle I strongly recommend using CSS.
However, if you really need server-generated graphics, the procedure is as follows:
Bitmap
(which is also an Image
)Graphics
object. (Hint: Graphics.FromImage()
)<img>
tag.Upvotes: 1
Reputation: 2975
You can do something like this:
<%@ Page Language="C#" ContentType="image/jpeg" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Text" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<%
Response.Clear();
int height = 100;
int width = 200;
Random r = new Random();
int x = r.Next(75);
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmp);
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(Color.Orange);
g.DrawRectangle(Pens.White, 1, 1, width-3, height-3);
g.DrawRectangle(Pens.Gray, 2, 2, width-3, height-3);
g.DrawRectangle(Pens.Black, 0, 0, width, height);
g.DrawString("The Code Project", new Font("Arial", 12, FontStyle.Italic),
SystemBrushes.WindowText, new PointF(x,50) );
bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
g.Dispose();
bmp.Dispose();
Response.End();
%>
Here's a link to the full article: http://www.codeproject.com/KB/aspnet/aspnet_web_graphics.aspx
Upvotes: 5