摘要:[WPF 筆記] Text Convert Image
使用::
//將列印字串格式化為圖片
FormattedText text = new FormattedText(
"文字字串",
CultureInfo.InvariantCulture,
FlowDirection.LeftToRight,
new Typeface("Segeo UI"),
14,
Brushes.Black);
string SourcePath = Directory.GetCurrentDirectory() + "\\Source.jpg";
string OutFileName = "Output.jpg";
WriteTextToImage(
SourcePath,
OutFileName,
text,
new Point(10, 10));
方法::
public void WriteTextToImage(string inputFile, string outputFile, FormattedText text, Point position)
{
BitmapImage bitmap = new BitmapImage(new Uri(inputFile)); // inputFile must be absolute path
DrawingVisual visual = new DrawingVisual();
using (DrawingContext dc = visual.RenderOpen())
{
dc.DrawImage(bitmap, new Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight));
dc.DrawText(text, position);
}
RenderTargetBitmap target = new RenderTargetBitmap(bitmap.PixelWidth, bitmap.PixelHeight,
bitmap.DpiX, bitmap.DpiY, PixelFormats.Default);
target.Render(visual);
BitmapEncoder encoder = null;
switch (System.IO.Path.GetExtension(outputFile))
{
case ".jpg":
//encoder = new PngBitmapEncoder();
encoder = new JpegBitmapEncoder();
break;
// more encoders here
}
if (encoder != null)
{
encoder.Frames.Add(BitmapFrame.Create(target));
using (FileStream outputStream = new FileStream(outputFile, FileMode.Create))
{
encoder.Save(outputStream);
}
}
}