Reputation: 403
I'm using a javascript framework that can only draw simple graphics objects or take a url to an image file. I need more complex graphics but there are too many combinations to create all the different possible images. Is it possible to intercept a file request at the server and return dynamically created content (png image) in its place ?
Upvotes: 1
Views: 504
Reputation: 150118
Sure, you can have a controller action return an image file. Here's an example of one that I wrote to write text to an image and return it.
Note that you probably want to use an OutputCache
and use VaryByParam
so that the output cache knows what query string parameters should be considered to decide if a request is for an image that was already generated or not.
[OutputCache(Duration=86400, VaryByParam="text;maxWidth;maxHeight")]
public ActionResult RotatedImage(string text, int? maxWidth, int? maxHeight)
{
SizeF textSize = text.MeasureString(textFont);
int width = (maxWidth.HasValue ? Math.Min(maxWidth.Value, (int)textSize.Width) : (int)textSize.Width);
int height = (maxHeight.HasValue ? Math.Min(maxHeight.Value, (int)textSize.Height) : (int)textSize.Height);
using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.DrawString(text, textFont, Brushes.Black, zeroPoint, StringFormat.GenericTypographic);
bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
}
}
}
Upvotes: 2