如何在WPF中显示AVIF格式图片?已解决WebP兼容问题
Hey there! Glad you got WebP working smoothly—let's fix that AVIF gap next. Since WPF's BitmapImage doesn't natively support AVIF, we'll decode the AVIF data into a format BitmapImage understands (like PNG, just like your WebP implementation). Here's how to make it work:
Step 1: Install a NuGet Package for AVIF Decoding
We'll use SixLabors.ImageSharp—a lightweight, cross-platform image library with full AVIF support. Open your NuGet Package Manager and install these two packages:
SixLabors.ImageSharpSixLabors.ImageSharp.Formats.Avif
Alternatively, use the Package Manager Console:
Install-Package SixLabors.ImageSharp Install-Package SixLabors.ImageSharp.Formats.Avif
Step 2: Update Your LoadImage Method
Replace the //TODO: display avif format image section with code that decodes the AVIF data and saves it to your MemoryStream as a PNG. Here's the full updated method:
using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Avif; private static BitmapImage LoadImage(byte[] imageData, string ext) { if (imageData == null || imageData.Length == 0) return null; var image = new BitmapImage(); using(var mem = new MemoryStream()) { if (ext == "webp") { // Your existing WebP handling code remains unchanged SimpleDecoder dec = new SimpleDecoder(); dec.DecodeFromBytes(imageData, imageData.Length).Save(mem, System.Drawing.Imaging.ImageFormat.Png); } else if (ext == "avif") { // Decode AVIF and save as PNG to the stream using (var avifImage = Image.Load(imageData, new AvifDecoder())) { avifImage.Save(mem, SixLabors.ImageSharp.Formats.Png.PngFormat.Instance); } } else { // For natively supported formats, write the original data directly mem.Write(imageData, 0, imageData.Length); } // Critical: Reset stream position to the start before initializing BitmapImage mem.Position = 0; image.BeginInit(); image.CreateOptions = BitmapCreateOptions.PreservePixelFormat; image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = null; image.StreamSource = mem; image.EndInit(); } image.Freeze(); return image; }
Alternative: Using ImageMagick (Magick.NET)
If you prefer using ImageMagick (another widely used image processing library), install the Magick.NET-Q16-AnyCPU NuGet package instead. Then update the AVIF branch like this:
using ImageMagick; // Inside the AVIF else-if block: using (var magickImage = new MagickImage(imageData)) { magickImage.Format = MagickFormat.Png; magickImage.Write(mem); }
Key Notes
- Always reset the
MemoryStreamposition to0after writing data—otherwise,BitmapImagewill read from the end of the stream and won't find any data to load. - Both libraries work with your existing
WebClientcode, so you don't need to change that part of your implementation.
内容的提问来源于stack exchange,提问作者bass9030

