微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将使用 InkCanvas 在画布上完成的工作保存到 UWP C# 中的图像文件?

如何解决如何将使用 InkCanvas 在画布上完成的工作保存到 UWP C# 中的图像文件?

我想在我的 UWP 应用中保存在画布上完成的工作。我正在使用 InkCanvas 在画布内的选定图像上绘制线条,我想将画布工作保存到新的图像文件中。

我在尝试保存文件后得到一个空白图像。我尝试了两种方法来保存文件

完成的工作:

xaml 代码

<Button Click="ShowPopup" Content="click me"/>
<Popup x:Name="IMG_G"  Width="600" Height="300" HorizontalAlignment="Left" ManipulationMode="All">
<Grid x:Name="img_grid" Height="300" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" ManipulationMode="Scale">
      <Image VerticalAlignment="Top" HorizontalAlignment="Left"
             x:Name="img" Stretch="Fill" Height="300" ManipulationMode="All">
      </Image>
      <Canvas x:Name="selectionCanvas" Width="600" Background="Transparent" Height="300"/>
      <InkCanvas x:Name="inker" />
      <InkToolbar x:Name="img_inktoolbar" TargetInkCanvas="{x:Bind inker}" 
                  VerticalAlignment="Top">
      </InkToolbar>
</Grid>
</Popup>
<Button Content="Save"
        Width="100"
        Height="25"
        HorizontalAlignment="Center"
        VerticalAlignment="Center" Click="BtnSave_Click"/>

背后的代码

public DrawLines()
    {
        InitializeComponent();

        inker.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Touch;
        inker.InkPresenter.UnprocessedInput.Pointerpressed += StartLine;
        inker.InkPresenter.UnprocessedInput.PointerMoved += ContinueLine;
        inker.InkPresenter.UnprocessedInput.PointerReleased += CompleteLine;
        inker.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
    }

private async void ShowPopup(object sender,RoutedEventArgs e)
    {
        var _filePicker = new fileopenpicker();
        _filePicker.SuggestedStartLocation = PickerLocationId.Desktop;
        _filePicker.viewmode = Pickerviewmode.Thumbnail;
        _filePicker.FileTypeFilter.Add(".bmp");
        _filePicker.FileTypeFilter.Add(".jpg");
        StorageFile _file = await _filePicker.PickSingleFileAsync();
        IRandomAccessstream imagestream = await _file.OpenAsync(FileAccessMode.Read);
        BitmapImage bmpimage = new BitmapImage();
        await bmpimage.SetSourceAsync(imagestream);
        img.source = bmpimage;
        IMG_G.IsOpen = true;
    }

private void StartLine(InkUnprocessedInput sender,PointerEventArgs args)
    {
        line = new Line();
        line.X1 = args.CurrentPoint.RawPosition.X;
        line.Y1 = args.CurrentPoint.RawPosition.Y;
        line.X2 = args.CurrentPoint.RawPosition.X;
        line.Y2 = args.CurrentPoint.RawPosition.Y;

        line.stroke = new SolidColorBrush(Colors.Purple);
        line.strokeThickness = 4;
        selectionCanvas.Children.Add(line);
    }

private void ContinueLine(InkUnprocessedInput sender,PointerEventArgs args)
    {
        line.X2 = args.CurrentPoint.RawPosition.X;
        line.Y2 = args.CurrentPoint.RawPosition.Y;
    }

private void CompleteLine(InkUnprocessedInput sender,PointerEventArgs args)
    {
        List<InkPoint> points = new List<InkPoint>();
        InkstrokeBuilder builder = new InkstrokeBuilder();


        InkPoint pointOne = new InkPoint(new Point(line.X1,line.Y1),0.5f);
        points.Add(pointOne);
        InkPoint pointTwo = new InkPoint(new Point(line.X2,line.Y2),0.5f);
        points.Add(pointTwo);

        Inkstroke stroke = builder.CreatestrokeFromInkPoints(points,System.Numerics.Matrix3x2.Identity);
        InkDrawingAttributes ida = inker.InkPresenter.copyDefaultDrawingAttributes();
        stroke.DrawingAttributes = ida;
        inker.InkPresenter.strokeContainer.Addstroke(stroke);
        selectionCanvas.Children.Remove(line);
    }

保存文件方法

private async void BtnSave_Click(object sender,RoutedEventArgs e)
    {
        StorageFolder pictureFolder = KNownFolders.SavedPictures;
        var file = await pictureFolder.CreateFileAsync("test2.bmp",CreationCollisionoption.ReplaceExisting);
        CanvasDevice device = CanvasDevice.GetSharedDevice();

        Canvasrendertarget rendertarget = new Canvasrendertarget(device,(int)img.ActualWidth,(int)img.ActualHeight,96);

        //get image's path
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        //Get the same image file copy which i selected to draw on in ShowPopup() but I actually wanted to get the edited canvas
        StorageFile Ifile = await folder.GetFileAsync("Datalog_2020_09_22_10_44_59_2_3_5_RSF.bmp");
        var inputFile = Ifile.Path;

        using (var ds = rendertarget.CreateDrawingSession())
        {
            ds.Clear(Colors.White);
            CanvasBitmap image = await CanvasBitmap.LoadAsync(device,inputFile);
            //var image = img2.source;
            // I want to use this too,but I have no idea about this

            ds.DrawImage(image);
            ds.DrawInk(inker.InkPresenter.strokeContainer.Getstrokes());
        }
        // save results           

        using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            await rendertarget.SaveAsync(fileStream,CanvasBitmapFileFormat.Jpeg,1f);
        }
    }

结果

想要的结果

注:箭头是我在图片上画的

Desired result

我用这种方法得到的结果

test2.bmp(图片由于某种原因被放大了)

test2.bmp

保存文件方法

private async void BtnSave_Click(object sender,RoutedEventArgs e)
    {
        rendertargetBitmap bitmap = new rendertargetBitmap();
        await bitmap.RenderAsync(selectionCanvas);
        Debug.WriteLine($"Capacity = {(uint)bitmap.PixelWidth},Length={(uint)bitmap.PixelHeight}");
        var pixelBuffer = await bitmap.GetPixelsAsync();
        Debug.WriteLine($"Capacity = {pixelBuffer.Capacity},Length={pixelBuffer.Length}");
        byte[] pixels = pixelBuffer.ToArray();
        var displayinformation = displayinformation.GetForCurrentView();
        StorageFolder pictureFolder = KNownFolders.SavedPictures;
        var file = await pictureFolder.CreateFileAsync("test2.bmp",CreationCollisionoption.ReplaceExisting);
        using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId,stream);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8,BitmapAlphaMode.Ignore,(uint)bitmap.PixelWidth,(uint)bitmap.PixelHeight,displayinformation.RawDpiX,displayinformation.RawDpiY,pixels);
            await encoder.FlushAsync();
        }
    }

这种方法的结果

出于某种原因,我得到了全黑图像

test2.bmp

All black image

任何帮助将不胜感激。对方法 2 的任何帮助都会更好。

解决方法

如何将使用 InkCanvas 在画布上完成的工作保存到 UWP C# 中的图像文件中?

您无需使用 RenderTargetBitmap 将 InkCanvas 保存为图像。 UWP InkCanvas 具有 SaveAsync 方法,可以将 StrokeContainer 流直接保存到图像文件。例如。

async void OnSaveAsync(object sender,RoutedEventArgs e)
{
    // We don't want to save an empty file
    if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count > 0)
    {
        var savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        savePicker.FileTypeChoices.Add("png with embedded ISF",new[] { ".png" });

        StorageFile file = await savePicker.PickSaveFileAsync();
        if (null != file)
        {
            try
            {
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    // Truncate any existing stream in case the new file
                    // is smaller than the old file.
                    stream.Size = 0;
                    await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                }
                
            }
            catch (Exception ex)
            {
             
            }
        }
    }
    else
    {
     
    }
}

更多细节请参考 UWP simple ink 代码示例场景 3

更新

我在尝试保存文件后得到一个空白图像。

以上代码只能保存InkCanvas笔画,我查看了你的代码,发现你没有在selectionCanvas中放置任何元素。所以 RenderTargetBitmapselectionCanvas 将黑空。请尝试使用img_grid替换。

抱歉,现在 InkToolbar 也被复制到图像上,以及我所做的墨水更改:(

这是特意设计的,RenderTargetBitmap 将呈现所有查看过的元素,对于您的场景,我们建议您在捕获屏幕和完成后重置。

,

我对方法 2 进行了一些更改并得到了预期的结果

保存文件的方法二

private async void BtnSave_Click(object sender,RoutedEventArgs e)
{
    // In order to hide the InkToolbar before the saving the image
    img_inktoolbar.Visibility = Visibility.Collapsed;

    RenderTargetBitmap bitmap = new RenderTargetBitmap();
    await bitmap.RenderAsync(img_grid);
    Debug.WriteLine($"Capacity = {(uint)bitmap.PixelWidth},Length={(uint)bitmap.PixelHeight}");
    var pixelBuffer = await bitmap.GetPixelsAsync();
    Debug.WriteLine($"Capacity = {pixelBuffer.Capacity},Length={pixelBuffer.Length}");
    byte[] pixels = pixelBuffer.ToArray();
    var displayInformation = DisplayInformation.GetForCurrentView();
    StorageFolder pictureFolder = KnownFolders.SavedPictures;
    var file = await pictureFolder.CreateFileAsync("test2.bmp",CreationCollisionOption.ReplaceExisting);
    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
    {
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId,stream);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8,BitmapAlphaMode.Ignore,(uint)bitmap.PixelWidth,(uint)bitmap.PixelHeight,displayInformation.RawDpiX,displayInformation.RawDpiY,pixels);
        await encoder.FlushAsync();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。