简体   繁体   中英

adding alternate text to a programmatically created image

So I have an ashx file that creates an image with text written on it.

//create the image for the string
Font f = new Font("Arial", 15F);
Graphics g = Graphics.FromImage(b);
SolidBrush whiteBrush = new SolidBrush(Color.FromArgb(0,71,133));
SolidBrush blackBrush = new SolidBrush(Color.White);
RectangleF canvas = new RectangleF(0, 0, 105, 45);
g.FillRectangle(whiteBrush, canvas);
context.Session["test"] = randomString;
g.DrawString(context.Session["test"].ToString(), f, blackBrush, canvas);
context.Response.ContentType = "image/gif";
b.Save(context.Response.OutputStream, ImageFormat.Gif);

When called, it creates the image I want, but realized that it doesn't have have an alt text option for accessibility purposes.

Any idea on how to add alternate text to an image?

In my aspx page I have this:

 <asp:Image ID="myImage" class="styleimage" src="ImageMaker.ashx" runat="server"/>

I have tried:

myImage.AlternateText = HttpContext.Current.Session["test"].ToString(); 

I receive a NullReferenceException .

This apparently happens because Session["test"] gets populated after the page load ( so the page loads, the image gets rendered, then the handler gets called).

How do I solve this?

You can create the session variable in your page_load and assign the randomString to it there.

You will then be able to access it in the handler to use in creating the image.

This way, you follow the timeline of the different events:

  • Page loads
  • Session variable gets created
  • Image element on the page gets rendered
  • Handler gets called
  • Session variable is referenced to get the string
  • Image gets generated
  • Profit!

The alt-text belongs to the img-tag which references the image your handler creates. Just put the alt tag there and you are good to go.

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