1
我正在使用一個JavaScript框架,它只能繪製簡單的圖形對象或將URL映射到圖像文件。我需要更復雜的圖形,但有太多的組合來創建所有不同的圖像。是否有可能在服務器上攔截文件請求並在其位置返回動態創建的內容(png圖像)?在ASP.NET中攔截文件請求,並返回動態創建的內容
我正在使用一個JavaScript框架,它只能繪製簡單的圖形對象或將URL映射到圖像文件。我需要更復雜的圖形,但有太多的組合來創建所有不同的圖像。是否有可能在服務器上攔截文件請求並在其位置返回動態創建的內容(png圖像)?在ASP.NET中攔截文件請求,並返回動態創建的內容
當然,你可以有一個控制器操作返回一個圖像文件。這裏有一個例子,我寫了一個寫文本到圖像並返回的例子。
請注意,您可能想要使用OutputCache
並使用VaryByParam
,以便輸出緩存知道應該考慮哪些查詢字符串參數來決定請求是否針對已經生成或未生成的圖像。
[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");
}
}
}
}
是的,看看處理程序:http://msdn.microsoft.com/en-us/library/5c67a8bd(v=vs.85).aspx – ppetrov
看起來有用,謝謝 –