【发布时间】:2014-02-16 18:28:55
【问题描述】:
.net(MVC/c# 等)中是否有一种“正确”的方式可以像本网站那样动态生成图像:http://www.fodey.com/generators/newspaper/snippet.asp 和/或,是否有第三方工具包可以帮助解决这些问题?
我知道低级图形 api,但很好奇如何以不需要大量手动编码的方式处理更高级的事情,如字体布局、分页等。
【问题讨论】:
标签: c# asp.net-mvc iis graphics
.net(MVC/c# 等)中是否有一种“正确”的方式可以像本网站那样动态生成图像:http://www.fodey.com/generators/newspaper/snippet.asp 和/或,是否有第三方工具包可以帮助解决这些问题?
我知道低级图形 api,但很好奇如何以不需要大量手动编码的方式处理更高级的事情,如字体布局、分页等。
【问题讨论】:
标签: c# asp.net-mvc iis graphics
那里有很多图像库。 IMO 没有“最佳实践”方式(“正确”、“著名”库)。有一种“标准”方法,您需要自己编写所有代码(如您所说),只使用 GDI+(System.Drawing)库,或者您可以查看:
唉,有时最好最快的解决方案仍然是编写自己的代码——取决于你想要达到的结果,你将花时间学习第三方库的 API,你可能会自己创建解决方案使用框架内置库。
【讨论】:
编写一个引用一些 WPF 程序集(PresentationFramework、PresentationCore、WindowsBase)的服务器端库会很简单,然后在背景图像上覆盖和图形或文本,类似于以下内容:
public ImageSource ApplyTextToBitmapSource(ImageSource backgroundImageSource, string text, Point location, FontFamily font, double fontSize, Brush foreground)
{
TextBlock tb = new TextBlock();
tb.Text = text;
tb.FontFamily = font;
tb.FontSize = fontSize;
tb.Foreground = foreground;
tb.Margin = new Thickness(location.X, location.Y, 0.0d, 0.0d);
Image image = new Image();
image.Stretch = Stretch.Uniform;
image.Source = backgroundImageSource;
Grid container = new Grid();
container.Width = backgroundImageSource.Width;
container.Height = backgroundImageSource.Height;
container.Background = new ImageBrush(backgroundImageSource);
container.Children.Add(tb);
return RenderElementToBitmap(container, new Size(backgroundImageSource.Width, backgroundImageSource.Height));
}
private ImageSource RenderElementToBitmap(FrameworkElement element, Size maxSize)
{
element.Measure(maxSize);
element.Arrange(new Rect(element.DesiredSize));
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)Math.Ceiling(element.ActualWidth),
(int)Math.Ceiling(element.ActualHeight), 96, 96, PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext ctx = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(element);
Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
Rect targetRect = new Rect(0.0d, 0.0d, bounds.Width, bounds.Height);
ctx.DrawRectangle(brush, null, targetRect);
}
renderTargetBitmap.Render(visual);
return renderTargetBitmap;
}
调用类似于以下内容:
FontFamily font = new FontFamily("Arial Bold");
ImageSource backgroundImageSource = new BitmapImage(new Uri("X:\\Dev\\WPF_Poster.png", UriKind.Absolute));
ImageSource imageSource = ApplyTextToBitmapSource(backgroundImageSource, "Overlayed Text", new Point(70.0d, 70.0d), font, 31.0d, Brushes.Blue);
希望这会有所帮助。如果您想了解更多信息,请告诉我。
【讨论】: