0

I want to display an image with format webp in my wpf solution, i used the following code.

Image image = new Image();
Binding imageBinding = new() { Source = bytes };
image.SetBinding(Image.SourceProperty, imageBinding);

Get the image via api call, thats why i use bytes and not a path.

The Problem is, when I run my application the image has a black background. How can I fix this?

JasonixDev
  • 19
  • 3
  • Otherwise, [this](https://stackoverflow.com/a/9564425/7252182) is how to convert a `byte[]` to an image. – mm8 Jan 23 '23 at 16:10
  • Sorry, it seems that the WebP codec does not support transparency. While `new BitmapImage(new Uri("https://www.gstatic.com/webp/gallery3/1_webp_ll.png"))` creates a bitmap with transparent background, `new BitmapImage(new Uri("https://www.gstatic.com/webp/gallery3/1_webp_ll.webp"))` does not. See also here: https://github.com/dotnet/wpf/issues/1436 – Clemens Jan 23 '23 at 16:25
  • Is there a way to set, the black pixels to transparent? – JasonixDev Jan 24 '23 at 13:36

1 Answers1

0

WPF and WEBP don't work well together. It's best to get rid of WEBP and switch to PNG. Workarounds like making black pixels transparent are difficult because a) the wrong pixels aren't always black and b) the image can also have "real" black pixels. These would then also be transparent.

However.

  1. In certain situations, WPF and WEBP also seem to work. The example code from Displaying Images in WPF helped me the most. There, the DecodePixelWidth attribute is used for BitmapImage. WEBP seems to work for certain values ​​of DecodePixelWidth. Prime numbers seem particularly suitable here. I used 997. It works fine for me.

  2. To make black pixels transparent you can use the MakeTransparent(Color) method of the Bitmap class. In order for this to work, you must first convert the BitmapImage into a bitmap and then back again. How to do this, is described in Converting BitmapImage to Bitmap and vice versa. This answer helped me the most.