From 9bf7b61e8d3490310212b1a6fce41d8afcd7f148 Mon Sep 17 00:00:00 2001 From: Steve McConnel Date: Wed, 28 Aug 2024 14:15:51 -0600 Subject: [PATCH] Reorder image fetching for GetImageFromClipboard to try PNG first This can help preserve transparency in copied images. --- CHANGELOG.md | 1 + .../Clipboarding/WindowsClipboard.cs | 33 ++++++++++--------- 2 files changed, 18 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 039e9f962..aafd5409a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Changed +- [SIL.Windows.Forms] Look for PNG data on clipboard before checking for plain image in WindowsClipboard.GetImageFromClipboard() in order to preserve transparency in copied images. - [SIL.Windows.Forms] Changed layout of SILAboutBox to accommodate wider SIL logo. - [SIL.Windows.Forms.Archiving] Split SIL.Archiving, moving Winforms portions (including dependency on L10nSharp) to SIL.Windows.Forms.Archiving. - [SIL.Archiving] Changed IMDIArchivingDlgViewModel.ArchivingPackage to return an IMDIPackage (instead of an IArchivingPackage). diff --git a/SIL.Windows.Forms/Clipboarding/WindowsClipboard.cs b/SIL.Windows.Forms/Clipboarding/WindowsClipboard.cs index 9f2ef4ed4..55009b09c 100644 --- a/SIL.Windows.Forms/Clipboarding/WindowsClipboard.cs +++ b/SIL.Windows.Forms/Clipboarding/WindowsClipboard.cs @@ -64,6 +64,23 @@ public PalasoImage GetImageFromClipboard() var textData = string.Empty; if (dataObject.GetDataPresent(DataFormats.UnicodeText)) textData = dataObject.GetData(DataFormats.UnicodeText) as string; + + // The order of operations here is a bit tricky. + // We want to maintain transparency in the original image, so we need to use the PNG format. + // Clipboard.ContainsImage() and Clipboard.GetImage() use the plain bitmap format which loses + // transparency. So here we explicitly ask for a PNG, and see if we can get it. + if (dataObject.GetDataPresent("PNG")) + { + var o = dataObject.GetData("PNG") as Stream; + try + { + return PalasoImage.FromImage(Image.FromStream(o)); + } + catch (Exception e) + { + ex = e; + } + } if (Clipboard.ContainsImage()) { PalasoImage plainImage = null; @@ -91,22 +108,6 @@ public PalasoImage GetImageFromClipboard() throw; } } - // the ContainsImage() returns false when copying an PNG from MS Word - // so here we explicitly ask for a PNG and see if we can convert it. - if (dataObject.GetDataPresent("PNG")) - { - var o = dataObject.GetData("PNG") as Stream; - try - { - return PalasoImage.FromImage(Image.FromStream(o)); - } - catch (Exception e) - { - // I'm not sure why, but previous versions of this code would continue trying other - // options at this point. - ex = e; - } - } // People can do a "copy" from the Windows Photo Viewer but what it puts on the System.Windows.Forms.Clipboard is a path, not an image if (dataObject.GetDataPresent(DataFormats.FileDrop))