我可以使用Blazor Client以编程方式生成和显示位图吗?

时间:2020-03-25 05:32:51

标签: c# blazor blazor-client-side

有什么方法可以在运行时生成位图,计算每个像素的RGBA值,然后在使用Blazor Client的上下文中在UI上显示该位图?

1 个答案:

答案 0 :(得分:1)

您可以使用ImageSharp,尽管它相当慢。然后只需转换为base64并用作<img />源即可。

请注意,显然在初始化(OnInitialized/OnParametersSet/OnAfterRender)期间似乎有一个限制,并且您将无法创建超过128x128x32的内容,渲染管线将冻结。但是,如果生成器代码是在页面生成后触发的,那么即使是较大的图像也可以正常工作。不过它很慢。

ImageGeneratorBase.razor.cs

using System;
using Microsoft.AspNetCore.Components;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.Primitives;
using SixLabors.Shapes;
using System.IO;

namespace StackOverflow.Sample1.Shared {
    public class ImageGeneratorBase : ComponentBase {
        [Parameter]
        public int Width { get; set; }
        [Parameter]
        public int Height { get; set; }

        protected string Image64 { get; set; }

        public void Generate() {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (Image img = new Image<Rgba32>(Width, Height))
                {
                    PathBuilder pathBuilder = new PathBuilder();
                    pathBuilder.SetOrigin(new PointF(0, 0));
                    pathBuilder.AddBezier(new PointF(Width / 5.0f, Height), new PointF(2 * Width / 5.0f, 0), new PointF(3 * Width / 5.0f, Height), new PointF(4 * Width / 5.0f, 0));
                    IPath path = pathBuilder.Build();

                    img.Mutate(ctx => ctx
                        .Fill(Color.Black)
                        .Draw(Color.White, 3, path)
                    );
                    img.SaveAsPng(outStream);

                }

                Image64 = "data:image/png;base64, " + Convert.ToBase64String(outStream.ToArray());
            }
            StateHasChanged();
        }
    }
}

ImageGenerator.razor

@inherits ImageGeneratorBase
@if (Image64 != null) {
    <img src=@Image64 />
}

Index.razor

@page "/"

<p>
    <Button @onclick=@(e => generator.Generate())>Generate image</Button>
</p>
<p>
    <ImageGenerator Width=256 Height=256 @ref=@generator />
</p>

@code {
    ImageGenerator generator;
}