简体   繁体   中英

Adding transparency to a SKBitmap image results in black background

I'm currently facing a problem showing a transparent image in a Xamarin.Forms Image view.

  1. The image is retrieved from the gallery, and converted to PNG format.
  2. Pixels are iterated and with some of them, their alpha value is adjusted.
  3. Bitmap is converted to SKBitmapImageSource and shown in an Image view.

Result (top), and original (bottom), taken on Android: Screenshot

The goal is to show the Image with a transparent background, but I can't get it to work. It keeps showing with a black background. Loading a transparent PNG file from internet works, so something in the process of conversion or image processing must go wrong.

Image retrieval and conversion:

SKBitmap source = SKBitmap.Decode(file.GetStream());
SKData data = SKImage.FromBitmap(source).Encode(SKEncodedImageFormat.Png, 100);
SKBitmap converted = SKBitmap.Decode(data);
SKBitmap result = ImageProcessor.AddTransparency(converted, 0.7f);

Transparency added:

    public static SKBitmap AddTransparency(SKBitmap bitmapSource, float treshold)
    {
        if (bitmapSource == null)
        {
            throw new ArgumentNullException(nameof(bitmapSource), $"{nameof(bitmapSource)} is null.");
        }

        var bitmapTarget = bitmapSource.Copy();

        // Calculate the treshold as a number between 0 and 255
        int value = (int)(255 * treshold);

        // loop trough every pixel
        int width = bitmapTarget.Width;
        int height = bitmapTarget.Height;

        for (int row = 0; row < height; row++)
        {
            for (int col = 0; col < width; col++)
            {
                var color = bitmapTarget.GetPixel(col, row);

                if (color.Red > value && color.Green > value && color.Blue > value)
                {
                    bitmapTarget.SetPixel(col, row, color.WithAlpha(0x00));
                }
            }
        }

        return bitmapTarget;
    }

Conversion to imagesource:

return SKBitmapImageSource.FromStream(SKImage.FromBitmap((SKBitmap)value).Encode().AsStream);

The problem is the AlphaType being set incorrectly. For the way you're doing the alpha conversion, the AlphaType should be set to AlphaType.Premul

Since it's a readonly property, copy the bitmap to a new one and set the correct alpha type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM