Jiri.Tywoniak
Jiri.Tywoniak

Reputation: 93

How to save image from clipboard to file in UWP

Is there any equivalent of

Clipboard.GetImage().Save(FileName, Imaging.ImageFormat.Jpeg)

for UWP (Windows Universal Platform)? I.e. saving the graphics image from clipboard into jpg format to file.

I am looking for example in vb.net/C#.

I have already started with

Dim datapackage = DataTransfer.Clipboard.GetContent()
If datapackage.Contains(StandardDataFormats.Bitmap) Then
Dim r As Windows.Storage.Streams.RandomAccessStreamReference = Await datapackage.GetBitmapAsync()

...

but I do not know how to continue (and even if I have even started correctly).

Upvotes: 9

Views: 3089

Answers (1)

Igor Ralic
Igor Ralic

Reputation: 15006

The first step is to try and get the image from the clipboard, if it exists:

var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
    IRandomAccessStreamReference imageReceived = null;
    try
    {
        imageReceived = await dataPackageView.GetBitmapAsync();
    }
    catch (Exception ex)
    {
    }

If it exists, launch a file save picker, choose where to save the image, and copy the image stream to the new file.

    if (imageReceived != null)
    {
        using (var imageStream = await imageReceived.OpenReadAsync())
        {
            var fileSave = new FileSavePicker();
            fileSave.FileTypeChoices.Add("Image", new string[] { ".jpg" });
            var storageFile = await fileSave.PickSaveFileAsync();

            using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                await imageStream.AsStreamForRead().CopyToAsync(stream.AsStreamForWrite());
            }
        }
    }
}

Upvotes: 8

Related Questions