Search code examples
image-processingfile-uploadblazor-webassembly

Control over format when using RequestImageFileAsync in Blazor WebAssembly


Blazor Web assembly has a convenience method that converts an IBrowserFile containing an image into a resized version - which is handy for resizing large images prior to uploading them.

This method takes a format as a string which determines the format of the output file.

Is there anywhere a list of valid formats that this property will accept? Can you specify the compression or bit depth values on the resulting file?

Currently, If I take an existing .jpg file and convert it using a format string of "jpg" the resulting file, although smaller in pixel dimensions is actually about double the size on disk. A 4000x3000 image at about 2.8MB can be "reduced" to a 2000x1500 image that's 7.7MB in size. Which is obviously not helping when the purpose is to reduce upload size. I could easily upload the 2.8MB file and resize it more efficiently on the server.

var imageFile = await file.RequestImageFileAsync("jpg", 2000, 2000);

This suggests I'm using the method incorrectly - but Microsoft's documentation on this method gives no clues as to what valid "Format" strings might, only stating that it is a string type. I've tried ".jpg", "JPEG", "jpg" - all of which seem to produce the same valid jpg file. What should I be passing here to actually reduce the file size?


Solution

  • See https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types

    It's actually not "image/jpg" but "image/jpeg". If you specify non-existent format, the fallback (at least for me) seems to be "image/png". That's why you always got a valid image but with the same filesize.