'How to serve bytes or images to Blazor-Maui App?
How would I go about creating a small server for use internally by a Blazor-Maui Desktop app?
I'm trying to serve images that are created on the fly into an img
tag:
<img src="/img-generator-service?data=576587" />
I'd like my Blazor-Maui app to instantiate a service that works as a webserver serving bytes to localhost, something like:
public async Task<byte[]> ImgGeneratorService(string data);
Or in the asp.net core pattern:
[HttpGet("img-generator-service")
public async Task<IActionResult> Get(string data);
Solution 1:[1]
From your image service, http://img-generator-service?data=576587, assuming 576587 is the image id and file format is jpeg, read the corresponding image from disk or memory as a byte array. Then convert it into base64 string, i.e, from binary to text using Convert.ToBase64String() and return the string.
From your app, if it is embedding a browser control, you can pass the data to
<img>
tag as a string like below,
<img src="@image">
@code {
protected string image;
protected async override Task OnInitializedAsync()
{
await base.OnInitializedAsync();
string bytes = GetImageFromService(576587);//Service returns string
image = string.Format("data:image/jpeg;base64,{0}", bytes);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nemo |