PROWAREtech

articles » archived » asp-net » webform-jpeg-output

ASP.NET: Image/JPEG Output

JPEG output in a WebForm / ASPX page (.NET Framework).

This is an ASPX page that is outputting a JPEG image. Set the ContentType="image/jpeg", call Response.Clear(), create a bitmap in memory and save it as a JPEG to the Response.OutputStream. This is an excellent way to create pie charts.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>
<%
	Response.Clear()
	Response.ContentType = "image/jpeg"
	Dim height As Integer = IIf(IsNumeric(Request.QueryString("height")), _
	 Request.QueryString("height"), 200)
	Dim width As Integer = IIf(IsNumeric(Request.QueryString("width")), _
	 Request.QueryString("width"), 200)
	Dim r As New Random
	Dim bmp As New Bitmap(width, height, PixelFormat.Format24bppRgb)
	Dim g As Graphics = Graphics.FromImage(bmp)
	g.SmoothingMode = SmoothingMode.AntiAlias
	g.Clear(Color.LightGray)
	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("Refresh Me!", New Font("Arial", 10, FontStyle.Bold), _
	 SystemBrushes.WindowText, New PointF(r.Next(50), r.Next(100)), _
	 New StringFormat(StringFormatFlags.DirectionVertical))
	g.FillRectangle(New SolidBrush(Color.FromArgb(r.Next(155), r.Next(255), _
	 r.Next(255), r.Next(255))), r.Next(width), r.Next(height), 100, 50)
	Dim x As Integer = r.Next(width)
	g.FillRectangle(New LinearGradientBrush(New Point(x, 0), New _
	 Point(x + 75, 100), Color.FromArgb(128, 0, 0, r.Next(255)), _
	 Color.FromArgb(255, r.Next(192, 255), r.Next(192, 255), r.Next(255))), x, r.Next(height), 75, 50)
	bmp.Save(Response.OutputStream, ImageFormat.Jpeg)
	g.Dispose()
	bmp.Dispose()
%>

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT