Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save image from clipboard to file in UWP

Tags:

c#

vb.net

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).

like image 240
Jiri.Tywoniak Avatar asked Nov 08 '15 12:11

Jiri.Tywoniak


1 Answers

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());
            }
        }
    }
}
like image 123
Igor Ralic Avatar answered Oct 17 '22 03:10

Igor Ralic