InputFile控件发出一个IBrowserFile类型。RequestImageFileAsync是IBrowserFile上一种方便的方法,用于调整图像大小和转换类型。结果仍然是一个IBrowserFile。
我使用以下示例来调整Blazor WebAssembly上传的图像的大小https://www.prowaretech.com/Computer/Blazor/Examples/WebApi/UploadImages。
不过我也需要将原始文件转换为base64,我不知道如何访问它。。。我试图找到文件的原始宽度和高度,将其传递给RequestImageFileAsync函数,但没有成功。。。我需要存储两个文件:原始文件和调整大小的文件。
你能帮我吗?
非常感谢!
一种方法是使用SixLabors.ImageSharp。基于ProWareTech的例子,类似这样的东西。。。
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;
}