[SvgThumbnailProvider] Preserve alpha transparency (#49301)

Render the WebView2 preview on a transparent background and keep the
alpha channel when resizing, so SVGs with transparency no longer render
as black thumbnails.

This also ensures we return an ARGB bitmap that matches what is the
expected in SvgThumbnailProvider.cpp with `WTS_ALPHATYPE::WTSAT_ARGB`.

<!-- Enter a brief description/summary of your PR here. What does it
fix/what does it change/how was it tested (even manually, if necessary)?
-->
## Summary of the Pull Request

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist

- [X] Closes: #36234
<!-- - [ ] Closes: #yyy (add separate lines for additional resolved
issues) -->
- [ ] **Communication:** I've discussed this with core contributors
already. If the work hasn't been agreed, this work might be rejected
- [X] **Tests:** Added/updated and all pass
- [ ] **Localization:** All end-user-facing strings can be localized
- [ ] **Dev docs:** Added/updated
- [ ] **New binaries:** Added on the required places
- [ ] [JSON for
signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json)
for new binaries
- [ ] [WXS for
installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs)
for new binaries and localization folder
- [ ] [YML for CI
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml)
for new test projects
- [ ] [YML for signed
pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml)
- [ ] **Documentation updated:** If checked, please file a pull request
on [our docs
repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys)
and link it here: #xxx

<!-- Provide a more detailed description of the PR, other things fixed,
or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

**The fix** is a single line — `_browser.DefaultBackgroundColor =
Color.Transparent` in `SvgThumbnailProvider.GetThumbnailImpl`. Without
it WebView2 composites onto an opaque background, so
`CapturePreviewAsync` returns a PNG with no usable alpha.

The native side already advertised `WTS_ALPHATYPE::WTSAT_ARGB`
(`SvgThumbnailProviderCpp/SvgThumbnailProvider.cpp:168`), so it was
promising Explorer an ARGB bitmap that the managed side never actually
produced.

**On the `ResizeImage` changes** (`Format32bppArgb` + dropping
`graphics.Clear(Color.White)`):
I measured these and they are strictly defensive — neither alters
output. `new Bitmap(w, h)`
already defaults to `Format32bppArgb`, and the `Clear` was entirely
overwritten by the
full-coverage `DrawImage` under `CompositingMode.SourceCopy`. I've kept
them because they
make the intent explicit and match the Gcode/Qoi/Bgcode providers, but
they are not
what fixes the bug.

**Also fixed:** `ResizeImage` never disposed its source image, leaking a
GDI bitmap per resize. The three sibling providers all dispose it; SVG
was the only one that didn't.

**Why the BMP round-trip doesn't lose the alpha:** the managed process
saves to a `.bmp`
(`Program.cs:35`) which the native handler reloads via `LoadImage`
(`SvgThumbnailProvider.cpp:167`).
The GDI+ BMP encoder writes 32bpp with the alpha bytes intact, and
`LoadImage` preserves
them, so transparency survives end to end — as the screenshots below
show.

## Screenshots

### Before

<img width="2289" height="1301" alt="image"
src="https://github.com/user-attachments/assets/b08c468a-fa74-4bf6-a007-f45212357503"
/>

### After

<img width="2279" height="1296" alt="image"
src="https://github.com/user-attachments/assets/df586ddc-70d3-4a5f-8939-5a1e3976e465"
/>

(FWIW, the blank icons are expected as those icons where incorrectly
exported)

<!-- Describe how you validated the behavior. Add automated tests
wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

- Viewed a folder of SVGs with transparent backgrounds in File Explorer
at various
  thumbnail sizes — see before/after above.
- Two tests added to `Preview.SvgThumbnailProvider.UnitTests`:
- `GetThumbnailShouldPreserveTransparentBackground` — renders an SVG
covering only
part of the viewBox, asserts the corner pixel stays at `A=0`. Fails
without this fix.
- `ResizeImageShouldPreserveAlphaChannel` — asserts `ResizeImage`
returns
    `Format32bppArgb` and does not force opacity.
- Full suite green locally: 15/15.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 7b3fb20d-6e9d-4fef-a5cd-f8921d28c220
This commit is contained in:
Pedro Lamas
2026-08-18 17:30:58 +01:00
committed by Boliang Zhang (from Dev Box)
parent fd61abe4fd
commit 1ebbef3ed1
2 changed files with 45 additions and 2 deletions

View File

@@ -2,6 +2,7 @@
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -116,6 +117,7 @@ namespace Microsoft.PowerToys.ThumbnailHandler.Svg
_browser.Visible = true;
_browser.Width = (int)cx;
_browser.Height = (int)cx;
_browser.DefaultBackgroundColor = Color.Transparent;
_browser.NavigationCompleted += async (object sender, CoreWebView2NavigationCompletedEventArgs args) =>
{
var a = await _browser.ExecuteScriptAsync($"document.getElementsByTagName('svg')[0].viewBox;");
@@ -258,7 +260,7 @@ namespace Microsoft.PowerToys.ThumbnailHandler.Svg
return null;
}
Bitmap destImage = new Bitmap(width, height);
Bitmap destImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
@@ -270,10 +272,11 @@ namespace Microsoft.PowerToys.ThumbnailHandler.Svg
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.Clear(Color.White);
graphics.DrawImage(image, 0, 0, width, height);
}
image.Dispose();
return destImage;
}

View File

@@ -4,6 +4,7 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
@@ -221,5 +222,44 @@ namespace SvgThumbnailProviderUnitTests
Assert.IsTrue(bitmap != null);
}
[TestMethod]
public void ResizeImageShouldPreserveAlphaChannel()
{
Bitmap source = new Bitmap(64, 64, PixelFormat.Format32bppArgb);
using (var graphics = Graphics.FromImage(source))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.Clear(Color.FromArgb(128, 255, 0, 0));
}
using Bitmap resized = SvgThumbnailProvider.ResizeImage(source, 32, 32);
Assert.IsNotNull(resized);
Assert.AreEqual(PixelFormat.Format32bppArgb, resized.PixelFormat);
Color center = resized.GetPixel(resized.Width / 2, resized.Height / 2);
Assert.AreEqual(128, center.A, "Resizing must not force the output to be opaque.");
}
[TestMethod]
public void GetThumbnailShouldPreserveTransparentBackground()
{
var svgBuilder = new StringBuilder();
svgBuilder.AppendLine("<svg viewBox=\"0 0 100 100\" xmlns=\"http://www.w3.org/2000/svg\">");
svgBuilder.AppendLine("\t<circle cx=\"50\" cy=\"50\" r=\"25\" fill=\"red\">");
svgBuilder.AppendLine("\t</circle>");
svgBuilder.AppendLine("</svg>");
SvgThumbnailProvider svgThumbnailProvider = new SvgThumbnailProvider(null);
svgThumbnailProvider.SvgContents = svgBuilder.ToString();
svgThumbnailProvider.SvgContentsReady.Set();
using Bitmap thumbnail = svgThumbnailProvider.GetThumbnail(256);
Assert.IsNotNull(thumbnail);
Assert.AreEqual(PixelFormat.Format32bppArgb, thumbnail.PixelFormat);
Assert.AreEqual(0, thumbnail.GetPixel(0, 0).A, "The thumbnail background must stay transparent.");
}
}
}