Chronostasys / Blazor.Cropper

A blazor library provides component to crop image
MIT License
84 stars 19 forks source link

[QUESTION] other types of files than IBrowserFile #58

Closed angelru closed 1 year ago

angelru commented 1 year ago

Hello,

I have a different case, with input, I select a PDF and then convert it to images and display it in my HTML page, is there a way to bind Cropper to an img src and display the selector?

angelru commented 1 year ago
        InvokeAsync(() =>
        {
            file = new StreamFile(new MemoryStream(Convert.FromBase64String(imgSrc)));
        });

Is there a more elegant solution? :)

Chronostasys commented 1 year ago
        InvokeAsync(() =>
        {
            file = new StreamFile(new MemoryStream(Convert.FromBase64String(imgSrc)));
        });

Is there a more elegant solution? :)

Hi @angelru ,
You can use a helper js function to get a byte array from the <img> and build a StreamFile from it.

async function getImgAsync(id) {
    var canvas = document.createElement('canvas');
    var img = document.getElementById(id);
    canvas.height = img.naturalHeight;
    canvas.width = img.naturalWidth;
    const ctx = canvas.getContext('2d')
    ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
        return await new Promise((rs, rv) => {
            canvas.toBlob(async b => {
                const bin = new Uint8Array(await new Response(b).arrayBuffer());
                rs(bin)
            });
        })
}
var bin = await JSRuntime.InvokeAsync<byte[]>("getImgAsync", "imgid");

this approach may have better performance if you are using dotnet version >= 6.0.

angelru commented 1 year ago

thanks