9

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

1 Answer 1

8

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());
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It looks good. And I like also that my 3 lines were OK, I mean good start (with exception of missing try/catch). jiri tywoniak
Note that though you have given the file a .jpg extension, it is still a BMP file. You need to convert the actual pixel data to save as JPG, PNG, etc.
@MahmoudAl-Qudsi Thank you for the great piece of advice. That saved a huge trouble for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.