📜 ⬆️ ⬇️

asp.net: dynamic image generation

Generating dynamic images is a very useful technique. Unfortunately, in asp.net there is no standard functionality that would implement the ability to dynamically create images. The purpose of this article is to show one of the ways to implement dynamic images in asp.net.

First we define the task:
- we need a user control that would accept a Bitmap instance and the type of the desired format (jpeg, png, bmp, gif) as input data;
- the control should provide output to the page of the image defined through Bitmap.
Define an enumeration with the allowed image format types:
public enum DynamicImageFormat {Gif = 0, Jpeg, Bmp, Png} * This code was highlighted with Source Code Highlighter .

This enumeration will be located in the body of the HTTP request handler class, which will be described below.
Now I bring the text of the class that implements the functionality we need:
public partial class DynamicImageControl: System.Web.UI.UserControl { public Bitmap DynamicBitmap { get ; set ; } public DynamicImageHandler.DynamicImageFormat DynamicImageFormat = DynamicImageHandler.DynamicImageFormat.Png; protected void Page_Load ( object sender, EventArgs e) { if (DynamicBitmap! = null ) { Guid _bitmapGuid = Guid .NewGuid (); Cache [_bitmapGuid.ToString ()] = DynamicBitmap; img.ImageUrl = String .Format ( "DynamicImageHandler.ashx? bitmap = {0} & format = {1}" , _bitmapGuid, ( int ) DynamicImageFormat); }}} * This code was highlighted with Source Code Highlighter .

It is necessary to clarify the following things:
- for dynamic image generation, I use the HTTP request handler DynamicImageHandler.ashx, the implementation of which I will give below;
- a reference to the Bitmap instance is transmitted to the processor through the Cache mechanism, a place where data can be stored within the application, the GUID of the saved Bitmap instance is transmitted to the processor via the query string, the type of image format is also transmitted.
Using Cache is not the best solution. I would be happy to hear alternatives.

Next, I give the handler code:
public void ProcessRequest ( HttpContext context) { string _bitmapGuid = context.Request.QueryString [ "bitmap" ]; if (! String .IsNullOrEmpty (_bitmapGuid)) { if (context.Cache [_bitmapGuid]! = null ) { Bitmap _bitmap = ( Bitmap ) context.Cache [_bitmapGuid]; if (_bitmap! = null ) {ImageFormat DynImageFormat = GetImgFormat (context); MemoryStream MemStream = new MemoryStream (); _bitmap.Save (MemStream, DynImageFormat); MemStream.WriteTo (context.Response.OutputStream); MemStream.Dispose (); _bitmap.Dispose (); context.Cache.Remove (_bitmapGuid); }}}} * This source code was highlighted with Source Code Highlighter .

Here, the handler receives and processes the parameters, loads Bitmap from Cache and, using the threading mechanism, writes an image in the required format to the context stream of the current page. The GetImgFormat function, which helps to handle the type of image format is defined as:
private ImageFormat GetImgFormat ( HttpContext context) {ImageFormat result = ImageFormat.Png; if (! String .IsNullOrEmpty (context.Request.QueryString [ "format" ])) {DynamicImageFormat _imgFormat = (DynamicImageFormat) Convert .ToInt32 (context.Request.QueryString [ "format" ]); switch (_imgFormat) { case DynamicImageFormat.Gif: result = ImageFormat.Gif; break ; case DynamicImageFormat.Jpeg: result = ImageFormat.Jpeg; break ; case DynamicImageFormat.Bmp: result = ImageFormat.Bmp; break ; case DynamicImageFormat.Png: result = ImageFormat.Png; break ; default : result = ImageFormat.Png; break ; }} return result; } * This source code was highlighted with Source Code Highlighter .

In addition, in the handler class, it is necessary to define the IsReusable boolean property, which will make it clear asp.net whether it is necessary to create a new handler instance with each request.
public bool IsReusable { get { return true ; }} * This source code was highlighted with Source Code Highlighter .

If we return IsReusable = false, then asp.net will create a new instance each time and in this way will slightly increase the load on the server.

Now I will demonstrate the use case of the obtained component and handler. Use the control in the specified way:
< form id = "form1" runat = "server" >
< asp: Label ID = "Label2" runat = "server" Text = "Dynamic creation of images:„ > </ asp: Label >
< uc1: DynamicImageControl ID = “DynamicImageControl1” runat = "server" />
< asp: Label ID = "Label1" runat = "server" Text = "End." > </ asp: Label >
</ form > This source code was highlighted with Source Code Highlighter .

In the code, we initialize the element fields. To do this, we define the simplest function that builds a Bitmap with the simplest captcha, so well known to everyone who has ever been registered on the web.
public static string GetRandomPassword ( int length) { Random rand = new Random (); StringBuilder password = new System.Text. StringBuilder (length); for ( int i = 1; i <= length; i ++) { int charIndex; do {charIndex = rand.Next (48, 123); } while (! ((charIndex> = 48 && charIndex <= 57) || (charIndex> = 65 && charIndex <= 90) || (charIndex> = 97 && charIndex <= 122))); password.Append ( Convert .ToChar (charIndex)); } return password.ToString (); } public Bitmap DrawPassword () { Bitmap _bitmap = new Bitmap (150, 30); Graphics _graphics = Graphics .FromImage (_bitmap); SolidBrush _foreColor = new SolidBrush (Color.White); SolidBrush _backColor = new SolidBrush (Color.FromArgb (0x73, 0x82, 0x9F)); _graphics.FillRectangle (_backColor, 0, 0, 150, 30); Font _font = new Font ( "Verdana" , 15); Point _point = new Point (5, 5); string _password = GetRandomPassword (10); _graphics.DrawString (_password, _font, _foreColor, _point); if (_graphics! = null ) _graphics.Dispose (); return _bitmap; } * This source code was highlighted with Source Code Highlighter .

Finally, the initialization of the control:
protected void Page_Load ( object sender, EventArgs e) {DynamicImageControl1.DynamicBitmap = DrawPassword (); DynamicImageControl1.DynamicImageFormat = DynamicImageHandler.DynamicImageFormat.Gif; } * This source code was highlighted with Source Code Highlighter .


It's all. As a result, we will be able to see such a picture on the screen:
')


The source code of the project with classes and an example is here:
ifolder.ru/6606116

PS: “there are no mistakes in the article!” - unfortunately, it is impossible to say this, but I will be glad if you pay attention to the error you found or suggest any improvements.

PPS: article posted on the website www.gotdotnet.ru
www.gotdotnet.ru/LearnDotNet/ASPNET/558721.aspx

Source: https://habr.com/ru/post/25606/


All Articles