Resizing Form Images using HTML Attributes

Recently I was wanting to build a Ruby on Rails project involving uploading images from a user in the browser. This is nice and all, but the image processing (resizing) must be done on the server-side, and if you have minimal resources you can only handle so much load before things get sluggish.

To work around this, the browser itself is more than capable of resizing images, but it takes a non-trivial amount of code to say "ensure the image uploaded is under 1000px wide and 70% jpeg quality". So I decided to fill this gap, creating a library called fileinput-image-resize.

How to use

All you need to do is add a single tiny (<1kb) JavaScript library to the page:

<script src="https://cdn.jsdelivr.net/gh/benkaiser/fileinput-image-resize@1.0.0/dist/bundle.js"></script>

And then place some special attributes on your input tags to control the resize behvaior:

<input type="file" data-max-width="500" data-max-height="500" data-quality="90" data-format="webp" />

And that's it! The server will receive the processed images as part of the form submission instead of the original selected image from the user.

For a full list of the options available for customizing the resize behavior, see the project README on GitHub.

A couple of notes

  • Images will have their EXIF metadata stripped. This is usually a benefit since it preserves the privacy of the users uploading the images, however if your specific web application requires this data then this approach isn't for you.
  • If a form submission reaches the server with an image that hasn't been resized, it means the user may have JavaScript disabled. In this case, you can reject the form and report an error to the user, or alternatively, fallback to resizing on the server.

What does this library enable?

If you're someone that likes to write Ruby on Rails applications with minimal need for client-side JavaScript, then this is perfect for pre-processing form image inputs. It means you don't need to do all the work of processing the images yourself with your JavaScript tooling, or waste CPU resources processing it server-side using a ruby gem. Just import one library and add some HTML attributes and you're done!

As always, source code is available here. Happy hacking!