Tom Cat
Tom Cat

Reputation: 345

Resize and Upload Images with Blazor WebAssembly

I am using the following sample to resize the uploaded images with Blazor WebAssembly https://www.prowaretech.com/Computer/Blazor/Examples/WebApi/UploadImages .

Still I need the original file too to be converted to base64 too and I don't know how can I access it... I tried to find the file's original width and height to pass its to RequestImageFileAsync function but no success... I need to store both files : the original one and the resized one.

Can you help me, please ?

Thank You Very Much !

Upvotes: 1

Views: 2917

Answers (1)

PirateQueen
PirateQueen

Reputation: 85

The InputFile control emits an IBrowserFile type. RequestImageFileAsync is a convenience method on IBrowserFile to resize the image and convert the type. The result is still an IBrowserFile.

One way to do what you are asking is with SixLabors.ImageSharp. Based on the ProWareTech example, something like this...

async Task OnChange(InputFileChangeEventArgs e)
    {
        var files = e.GetMultipleFiles(); // get the files selected by the users
        foreach(var file in files)
        {
            //Original-sized file
            var buf1 = new byte[file.Size];
            using (var stream = file.OpenReadStream())
            {
                await stream.ReadAsync(buf1); // copy the stream to the buffer
            }
            origFilesBase64.Add(new ImageFile { base64data = Convert.ToBase64String(buf1), contentType = file.ContentType, fileName = file.Name }); // convert to a base64 string!!
            
            //Resized File
            var resizedFile = await file.RequestImageFileAsync(file.ContentType, 640, 480); // resize the image file
            var buf = new byte[resizedFile.Size]; // allocate a buffer to fill with the file's data
            using (var stream = resizedFile.OpenReadStream())
            {
                await stream.ReadAsync(buf); // copy the stream to the buffer
            }
            filesBase64.Add(new ImageFile { base64data = Convert.ToBase64String(buf), contentType = file.ContentType, fileName = file.Name }); // convert to a base64 string!!
        }
        //To get the image Sizes for first image
        ImageSharp.Image origImage = Image.Load<*imagetype*>(origFilesBase64[0])
        int origImgHeight = origImage.Height;
        int origImgWidth = origImage.Width;

        ImageSharp.Image resizedImage = Image.Load<*imagetype*>(filesBase64[0])
        int resizedImgHeight = resizedImage.Height;
        int resizedImgWidth = resizedImage.Width;
    }

Upvotes: 3

Related Questions