【问题标题】:Adding transparency to a SKBitmap image results in black background向 SKBitmap 图像添加透明度会导致黑色背景
【发布时间】:2020-08-13 06:51:40
【问题描述】:

我目前在 Xamarin.Forms 图像视图中显示透明图像时遇到问题。

  1. 从图库中检索图像,并将其转换为 PNG 格式。
  2. 像素会被迭代,其中一些像素会调整其 alpha 值。
  3. 位图转换为 SKBitmapImageSource 并显示在图像视图中。

在 Android 上拍摄的结果(上)和原始(下): Screenshot

目标是显示具有透明背景的图像,但我无法让它工作。它一直以黑色背景显示。从互联网加载透明PNG文件是可行的,因此在转换或图像处理过程中一定会出错。

图像检索与转换:

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);

增加透明度:

    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;
    }

转换为图像源:

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

【问题讨论】:

  • 确保黑色是真正的黑色。包括 irfanview 在内的许多图像查看器无法显示透明度并将其显示为黑色..
  • 尝试将像素点除alpha值为0以外为真黑,但没有成功。

标签: c# image-processing xamarin.forms .net-standard skiasharp


【解决方案1】:

问题是 AlphaType 设置不正确。对于您进行 alpha 转换的方式,应将 AlphaType 设置为 AlphaType.Premul

由于它是只读属性,请将位图复制到一个新的并设置正确的 alpha 类型

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2023-03-15
    • 2016-12-26
    • 2012-06-26
    • 2018-12-03
    • 2013-11-18
    相关资源
    最近更新 更多