如何使用 UWP 在图像上绘制文本并保存(for Windows 10)

How to draw text on an image and save it using UWP (for Windows 10)

我想在 UWP 中的模板图像上绘制文本(Windows 10),然后能够保存图像(以便用户可以打印或共享它)。

我玩过 canvas 控件,甚至玩过 nuget 的 Win2D 包。任何有关执行此操作的最佳方法的建议都将受到赞赏。下面是我离开的地方的示例代码。

XAML

<Page
x:Class="DrawTextExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DrawTextExample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:canvas="using:Microsoft.Graphics.Canvas.UI.Xaml"
mc:Ignorable="d">

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button Name="btnSaveImage" Content="Save the image" Margin="10" Click="btnSaveImage_Click" />

    <Grid Name="MyCreatedImage">
        <Image Name="imgName" Stretch="UniformToFill" Source="Assets/HelloMyNameIs.jpg" />
        <TextBlock Name="lblName" Text="McFly" Margin="20,100,20,20" FontSize="36"/>
    </Grid>
</StackPanel>

代码隐藏

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace DrawTextExample {
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private async void btnSaveImage_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
            var bitmap = new RenderTargetBitmap();
            await bitmap.RenderAsync(MyCreatedImage);
        }
    }
}

图片 (HelloMyNameIs.jpg)

I want to draw text on a template image in UWP (for Windows 10), and then be able to save the image (so the user could print or share it).

根据您的代码片段,您正在尝试使用能够满足您要求的RenderTargetBitmap。这个 class 可以将 ImageTextBlock 一起渲染成一个图像。您的代码片段只是缺乏保存。您可以按如下方式保存渲染图像:

private async void btnSaveImage_Click(object sender, RoutedEventArgs e)
{
    RenderTargetBitmap bitmap = new RenderTargetBitmap();
    await bitmap.RenderAsync(MyCreatedImage);

    var pixelBuffer = await bitmap.GetPixelsAsync();
    var pixels = pixelBuffer.ToArray();
    var displayInformation = DisplayInformation.GetForCurrentView();
    StorageFolder pictureFolder = KnownFolders.SavedPictures;
    var file = await pictureFolder.CreateFileAsync("test2.jpg", CreationCollisionOption.ReplaceExisting);
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                             BitmapAlphaMode.Premultiplied,
                             (uint)bitmap.PixelWidth,
                             (uint)bitmap.PixelHeight,
                             displayInformation.RawDpiX,
                             displayInformation.RawDpiY,
                             pixels);
        await encoder.FlushAsync();
    }
}

您也可以尝试使用Win2D which may be recommended. You can draw images, draw text and draw shapes as you want. It provides the CanvasBitmap.SaveAsync方法保存结果。比如下面的demo展示了如何在图片上绘制文字并保存到图片文件夹中。

Uri imageuri = new Uri("ms-appx:///Assets/HelloMyNameIs.jpg");
StorageFile inputFile = await StorageFile.GetFileFromApplicationUriAsync(imageuri);
BitmapDecoder imagedecoder;
using (var imagestream = await inputFile.OpenAsync(FileAccessMode.Read))
{
    imagedecoder =await BitmapDecoder.CreateAsync(imagestream);
}  
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, imagedecoder.PixelWidth, imagedecoder.PixelHeight, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
    ds.Clear(Colors.White);
    CanvasBitmap image = await CanvasBitmap.LoadAsync(device, inputFile.Path, 96);
    ds.DrawImage(image);
    ds.DrawText(lblName.Text, new System.Numerics.Vector2(150, 150), Colors.Black);
}
string filename = "test1.png";
StorageFolder pictureFolder = KnownFolders.SavedPictures;
var file = await pictureFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
}

如果您想在图片上绘制个性文字,您可以考虑使用 InkCanvasDrawInk. Details you may reference this thread